前段时间在一个项目中使用到结构体数组来存储产品不同型号的参数,使程序通用化,便于测试和快速生产。由于之前很少使用结构体数组,在初始化时遇到了一点小阻碍,于是便想到对于结构体和其数组的初始化操作做一个小总结:
结构体
结构体初始化其实有多种方式,以一个经典模板为例:
#include <stdio.h>
struct Student{
char *name;
int age;
float score;
}stu = {"小王",18,80.5};
int main(){
printf("%s %d %.2f\r\n",stu.name,stu.age,stu.score);
return 0;
}
输出如下:
也可以部分初始化:
#include <stdio.h>
struct Student{
char *name;
int age;
float score;
}stu = {.name = "小王",.age = 18};
int main(){
//printf("%s %d %.2f\r\n",stu.name,stu.age,stu.score);
printf("%s %d\r\n",stu.name,stu.age);
return 0;
}
但是在这种方式下需要注意在指明的成员后接未指明的成员时,该未指明成员默认是按顺序初始化指明成员的下一位成员变量:
#include <stdio.h>
struct Student{
char *name;
int age;
float score;
}stu = {.score = 60.5,.name = "小王",18,90.5};
int main(){
printf("%s %d %.2f\r\n",stu.name,stu.age,stu.score);
return 0;
}
可以看到开始指明初始化了score和name,但是结果却是后面的18和90.5按顺序初始化了name后面的age与score,覆盖了前面指明的60.5。
除了在声明结构体时初始化,也可以在定义变量时初始化,或者定义后再赋值,格式同上面类似:
struct Student{
char *name;
int age;
float score;
};
struct Student stu = {"小王",18,80.5};
struct Student stu = {.name = "小王",.age = 18,.score = 80.5};
struct Student stu;
stu.name = "小王";
stu.age = 18;
stu.score = 80.5;
struct Student stu;
struct Student *pstu = &stu;
pstu->name = "小王";
pstu->age = 18;
pstu->score = 80.5;
上述方法都可以得到正确的输出。
但是同数组一样,下面的方法是错误的:
struct Student stu;
stu = {"小王",18,80.5};
结构体数组
与多维数组的初始化类似,在分清结构体的初始化方式后,结构体数组就很明了了,首先是声明时初始化:
#include <stdio.h>
struct Student{
char *name;
int age;
float score;
}stu[3] = { //或者不写明成员数量stu[]
{"小王",18,80.5},
{"小李",19,85.5},
{"小赵",20,90.5}
};
int main(){
int i,arrayNum;
arrayNum = sizeof(stu) / sizeof(struct Student);
for(i = 0;i < arrayNum;i++)
printf("%s %d %.2f\r\n",stu[i].name,stu[i].age,stu[i].score);
return 0;
}
注意花括号与花括号之间使用的是逗号。
struct Student{
char *name;
int age;
float score;
}stu[3] = {
"小王",18,80.5,
"小李",19,85.5,
"小赵",20,90.5
};
struct Student{
char *name;
int age;
float score;
}stu[3] = {
[0].name = "小王",18,80.5,
[1].name = "小李",19,85.5,
[2].name = "小赵",20,90.5
};
均可得到如下的正确输出:
上述三种方式在定义时初始化同样适用:
struct Student{
char *name;
int age;
float score;
};
int main(){
int i,arrayNum;
struct Student stu[3] = {
"小王",18,80.5,//{"小王",18,80.5},
"小李",19,85.5,//[1].name = "小李",19,85.5,
"小赵",20,90.5
};
arrayNum = sizeof(stu) / sizeof(struct Student);
for(i = 0;i < arrayNum;i++)
printf("%s %d %.2f\r\n",stu[i].name,stu[i].age,stu[i].score);
return 0;
}
在定义后再初始化操作同第一节结构体初始化,只不过加了下标,不在赘述。而且下面这种方式仍为错误:
struct Student stu[3];
stu[3] = { //或stu =
"小王",18,80.5,
"小李",19,85.5,
"小赵",20,90.5
};