结构体变量可以作数组元素。
时间: 2023-08-18 19:09:14 浏览: 53
是的,结构体变量可以作为数组元素。这种用法通常在需要处理多个具有相同属性的对象时很有用。例如,我们可以定义一个结构体来表示学生的信息,然后创建一个学生数组,每个元素都是一个学生结构体变量。这样,我们就可以很方便地访问每个学生的信息。
下面是一个简单的例子:
```
struct Student {
char name[20];
int age;
float score;
};
int main() {
struct Student students[3];
strcpy(students[0].name, "Alice");
students[0].age = 18;
students[0].score = 90.5;
strcpy(students[1].name, "Bob");
students[1].age = 19;
students[1].score = 80.0;
strcpy(students[2].name, "Charlie");
students[2].age = 20;
students[2].score = 85.5;
// 访问学生信息
printf("%s is %d years old and got a score of %.1f\n", students[0].name, students[0].age, students[0].score);
printf("%s is %d years old and got a score of %.1f\n", students[1].name, students[1].age, students[1].score);
printf("%s is %d years old and got a score of %.1f\n", students[2].name, students[2].age, students[2].score);
return 0;
}
```
这个例子定义了一个包含三个学生信息的数组,并访问了每个学生的姓名、年龄和分数。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)