举一个结构体数组的例子
时间: 2023-03-30 12:01:24 浏览: 82
可以举一个学生信息的结构体数组的例子,如下所示:
struct student {
char name[20];
int age;
float score;
};
struct student stu_arr[3] = {
{"Tom", 18, 90.5},
{"Jerry", 19, 88.5},
{"Alice", 20, 92.}
};
这个结构体数组包含了三个学生的信息,每个学生都有姓名、年龄和成绩三个属性。可以通过下标来访问每个学生的信息,例如 stu_arr[].name 表示第一个学生的姓名。
相关问题
c语言结构体数组作为形参是怎样的?举个例子
好的,关于你问的问题,我可以回答。在C语言中,结构体数组作为形参时,可以通过指针传递,也可以直接传递结构体数组。这可以用来处理需要对多个结构体进行操作的函数。
举个例子,假设我们有一个结构体Person,字段包括姓名和年龄。我们想写一个函数来打印多个Person的信息,可以这样定义函数:
```
void printPersonArray(Person *persons, int n) {
for (int i = 0; i < n; i++) {
printf("%s is %d years old.\n", persons[i].name, persons[i].age);
}
}
```
这个函数以结构体数组Person *persons和其长度n作为参数。在函数内部,我们可以通过下标访问结构体数组的各个元素,并输出它们的信息。
当我们需要调用这个函数时,可以这样做:
```
Person persons[3] = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 35}};
printPersonArray(persons, 3);
```
这个例子创建了一个有三个元素的Person结构体数组,并将其传递给printPersonArray函数。函数会打印每个人的姓名和年龄。
希望这个例子可以帮助你更好地理解结构体数组作为形参的用法。
结构体指针数组举个例子
结构体指针数组是指一个数组中的每个元素都是指向结构体的指针。通过使用结构体指针数组,可以方便地管理和操作多个结构体对象。
举个例子,假设我们有一个学生信息的结构体,包含学生的姓名和年龄:
```c
typedef struct {
char name[20];
int age;
} Student;
```
现在我们需要管理多个学生的信息,可以使用结构体指针数组来实现。首先定义一个结构体指针数组,并为每个学生分配内存空间:
```c
Student* students[3]; // 定义一个包含3个学生的结构体指针数组
students[0] = (Student*)malloc(sizeof(Student)); // 为第一个学生分配内存空间
strcpy(students[0]->name, "Alice"); // 设置第一个学生的姓名
students[0]->age = 18; // 设置第一个学生的年龄
students[1] = (Student*)malloc(sizeof(Student)); // 为第二个学生分配内存空间
strcpy(students[1]->name, "Bob"); // 设置第二个学生的姓名
students[1]->age = 19; // 设置第二个学生的年龄
students[2] = (Student*)malloc(sizeof(Student)); // 为第三个学生分配内存空间
strcpy(students[2]->name, "Charlie"); // 设置第三个学生的姓名
students[2]->age = 20; // 设置第三个学生的年龄
```
通过结构体指针数组,我们可以方便地访问和修改每个学生的信息。例如,可以打印出每个学生的姓名和年龄:
```c
for (int i = 0; i < 3; i++) {
printf("学生姓名:%s,年龄:%d\n", students[i]->name, students[i]->age);
}
```
这样就可以输出每个学生的信息了。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)