编译环境:
gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.9)
测试结构体声明如下:
struct person
{
int age;
char name[256];
}
第一种: 先定义变量, 用[.]或者[->]引用的方式初始化
//栈空间
struct person p1;
p1.age = 20;
strcpy(p1.name, "xiaoming");
printf("age: %d\n", p1.age);
printf("name: %s\n", p1.name);
//堆空间
struct person * p2 = NULL;
p2 = (struct person *)malloc(sizeof(*p2))
if(p2 != NULL)
{
p2->age = 22;
strcpy(p2->name, "xiaohong");
printf("age: %d\n", p2->age);
printf("name: %s\n", p2->name);
free(p2);
p2 = NULL;
}
第二种: 显示按顺序在大括号中赋值初始化
/**栈空间**/
//定义的时候同时初始化, 必须注意顺序
struct person p1 = {18, "xiaoming"};
printf("age: %d\n", p1.age);
printf("name: %s\n", p1.name);
//可先定义后初始化
struct person p2;
p2 = (struct person){19, "xiaohong"};
printf("age: %d\n", p2.age);
printf("name: %s\n", p2.name);
/**堆空间**/
//先申请好内存,后进行初始化
struct person * p3 = NULL;
p3 = (struct person *)malloc(sizeof(*p3));
if(p3 != NULL)
{
*p3 = (struct person){20, "xiaohua"};
printf("age: %d\n", p3->age);
printf("name: %s\n", p3->name);
free(p3);
p3 = NULL;
}
第三种: 在大括号中[.] + [成员]初始化方式, 这种方式linux内核常用与初始化顺序无关;如果有重复的,最后一次初始化的值生效。(ps: 大括号中的最后一个逗号可加可不加)
/**栈空间**/
//定义的同时初始化
struct person p1 =
{
.age = 20,
.name = "xiaoming",
.age = 21,
};
printf("age: %d\n", p1.age);
printf("name: %s\n", p1.name);
//先定义再初始化
struct person p2;
p2 = (struct person)
{
.age = 21,
.name = "xiaohong",
};
printf("age: %d\n", p2.age);
printf("name: %s\n", p2.name);
/**堆空间**/
//先申请内存后初始化
struct person * p3 = NULL;
p3 = (struct person *)malloc(sizeof(*p3));
if(p3 != NULL)
{
*p3 = (struct person)
{
.age = 22,
.name = "xiaohua",
};
printf("age: %d\n", p3->age);
printf("name: %s\n", p3->name);
free(p3);
p3 = NULL;
}