在C语言中,静态结构初始化是指在程序运行时为结构体变量分配内存,并将结构体成员初始化为预定义的值。静态结构初始化可以通过以下几种方式实现:
struct Student {
int id;
char name[20];
float score;
};
struct Student stu = {1, "John", 90.5};
memset
函数:#include<string.h>
struct Student {
int id;
char name[20];
float score;
};
struct Student stu;
memset(&stu, 0, sizeof(stu));
designated initializers
(C99标准新增特性):struct Student {
int id;
char name[20];
float score;
};
struct Student stu = {.id = 1, .name = "John", .score = 90.5};
compound literals
(C99标准新增特性):struct Student {
int id;
char name[20];
float score;
};
struct Student *p = (struct Student[]){ {1, "John", 90.5} };
在使用静态结构初始化时,需要注意以下几点:
NULL
或者(type *)0
来初始化。{}
来初始化。{}
来初始化。推荐的腾讯云相关产品:
产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云