在C语言中,结构体数组的赋值可以通过以下几种方法:
- 逐个元素赋值:
```c
include
typedef struct { int a; float b; } Student;
int main() { Student students[3] = { {1, 90.5}, {2, 85.0}, {3, 92.0} };
for (int i = 0; i < 3; i++) {
printf("学生 %d: a = %d, b = %.1f\n", i + 1, students[i].a, students[i].b);
}
return 0;
} ```
- 使用
memset
函数:
```c
include
include
typedef struct { int a; float b; } Student;
int main() { Student students[3]; memset(students, 0, sizeof(students));
students[0].a = 1;
students[0].b = 90.5;
students[1].a = 2;
students[1].b = 85.0;
students[2].a = 3;
students[2].b = 92.0;
for (int i = 0; i < 3; i++) {
printf("学生 %d: a = %d, b = %.1f\n", i + 1, students[i].a, students[i].b);
}
return 0;
} ```
- 使用循环逐个元素赋值:
```c
include
typedef struct { int a; float b; } Student;
int main() { Student students[3];
students[0].a = 1;
students[0].b = 90.5;
students[1].a = 2;
students[1].b = 85.0;
students[2].a = 3;
students[2].b = 92.0;
for (int i = 0; i < 3; i++) {
printf("学生 %d: a = %d, b = %.1f\n", i + 1, students[i].a, students[i].b);
}
return 0;
} ```
以上三种方法都可以实现结构体数组的赋值。