C语言,有6个结构体指针数组,如何进行赋值
时间: 2024-01-13 10:04:03 浏览: 50
如果有6个结构体指针数组,我们可以使用循环语句对每个结构体指针数组进行赋值,具体步骤如下:
1. 定义结构体类型和结构体指针数组;
2. 定义6个结构体变量;
3. 定义6个结构体指针数组;
4. 使用循环语句对每个结构体指针数组进行赋值。
下面是示例代码:
```c
#include <stdio.h>
struct Student {
char name[20];
int age;
};
int main() {
struct Student stu1 = {"Tom", 18};
struct Student stu2 = {"Jerry", 19};
struct Student stu3 = {"Alice", 20};
struct Student stu4 = {"Bob", 21};
struct Student stu5 = {"David", 22};
struct Student stu6 = {"Lucy", 23};
struct Student* arr1[3];
struct Student* arr2[3];
struct Student* arr3[3];
struct Student* arr4[3];
struct Student* arr5[3];
struct Student* arr6[3];
// 对每个结构体指针数组进行赋值
for (int i = 0; i < 3; i++) {
arr1[i] = &stu1;
arr2[i] = &stu2;
arr3[i] = &stu3;
arr4[i] = &stu4;
arr5[i] = &stu5;
arr6[i] = &stu6;
}
// 输出每个结构体指针数组中第一个元素所指向的结构体的姓名和年龄
printf("arr1[0]->name = %s, arr1[0]->age = %d\n", arr1[0]->name, arr1[0]->age);
printf("arr2[0]->name = %s, arr2[0]->age = %d\n", arr2[0]->name, arr2[0]->age);
printf("arr3[0]->name = %s, arr3[0]->age = %d\n", arr3[0]->name, arr3[0]->age);
printf("arr4[0]->name = %s, arr4[0]->age = %d\n", arr4[0]->name, arr4[0]->age);
printf("arr5[0]->name = %s, arr5[0]->age = %d\n", arr5[0]->name, arr5[0]->age);
printf("arr6[0]->name = %s, arr6[0]->age = %d\n", arr6[0]->name, arr6[0]->age);
return 0;
}
```
在上面的示例代码中,我们定义了一个结构体类型和6个结构体变量,以及6个结构体指针数组。我们使用循环语句对每个结构体指针数组进行赋值,将每个结构体指针数组的元素指向对应的结构体变量。最终输出每个结构体指针数组中第一个元素所指向的结构体的姓名和年龄,以arr1为例,输出结果为arr1[0]->name = Tom, arr1[0]->age = 18。