struct结构体中成员是数组
时间: 2023-05-24 21:06:32 浏览: 47
有可能,结构体中的成员可以是数组类型。例如:
struct student {
char name[20];
int scores[5];
};
这个结构体表示一个学生的姓名和五个科目的成绩,其中成绩以数组的方式存储。当定义一个该结构体类型的变量时,我们可以像下面这样使用它:
struct student s;
strcpy(s.name, "John");
s.scores[0] = 90;
s.scores[1] = 85;
s.scores[2] = 92;
s.scores[3] = 78;
s.scores[4] = 88;
这里,我们先把学生的姓名设为“John”,然后给他的五个科目分别赋值。注意,我们使用“s.scores[i]”来访问结构体中的数组成员。
相关问题
struct结构体中成员是数组怎么赋值
在结构体中定义的数组成员可以通过循环或一次性赋值进行初始化。以下是两种方法的示例:
1.循环赋值
struct student {
int id;
char name[20];
int scores[5];
};
// 初始化scores数组
struct student st;
for (int i = 0; i < 5; i++) {
st.scores[i] = i * 10;
}
2.一次性赋值
struct student {
int id;
char name[20];
int scores[5];
};
// 初始化scores数组
struct student st = {
.id = 1,
.name = "John",
.scores = {70, 80, 90, 85, 95},
};
c语言结构体中二维数组初始化
在C语言中,结构体中的二维数组可以通过以下方式进行初始化:
1.定义结构体类型和二维数组类型:
```
typedef struct {
int arr[2][3];
} MyStruct;
```
2.定义结构体变量并初始化二维数组:
```
MyStruct myStruct = {
{1, 2, 3},
{4, 5, 6}
};
```
这里的初始化方式与定义一个2×3的数组的方式相同。
3.也可以使用指针的方式初始化:
```
MyStruct myStruct = {
.arr = (int[2][3]){{1, 2, 3}, {4, 5, 6}}
};
```
这里使用了C99标准中的指定初始化器,其中".arr"表示初始化结构体中的"arr"成员,"(int)"表示将后面的大括号中的元素转换为int类型的二维数组,最后大括号中的元素就是二维数组的初始化值。