C语言如何创建一个空的结构体数组
时间: 2023-04-02 12:00:42 浏览: 129
你可以使用以下语句来创建一个空的结构体数组:
struct 结构体名 数组名[数组长度];
例如,如果你要创建一个名为 Student 的结构体数组,可以使用以下语句:
struct Student studentArray[10];
这将创建一个包含 10 个元素的空的 Student 结构体数组。
相关问题
用c语言指针实现一个结构体数组对另一个结构体数组的赋值
以下是用C语言指针实现一个结构体数组对另一个结构体数组的赋值的示例代码:
```c
#include <stdio.h>
#include <string.h>
struct student {
int num;
char name[10];
char sex;
double height;};
int main() {
struct student stus1[3] = {{1001, "Tom", 'M', 1.75}, {1002, "Jerry", 'F', 1.65}, {1003, "Mike", 'M', 1.80}};
struct student stus2[3];
struct student *p1, *p2;
p1 = stus1;
p2 = stus2;
memcpy(p2, p1, sizeof(stus1));
for (int i = 0; i < 3; i++) {
printf("stus2[%d]: num=%d, name=%s, sex=%c, height=%.2f\n", i, (p2+i)->num, (p2+i)->name, (p2+i)->sex, (p2+i)->height);
}
return 0;
}
```
解释如下:
1. 定义了一个结构体`student`,包含学号、姓名、性别和身高四个成员变量。
2. 定义了两个结构体数组`stus1`和`stus2`,分别用于存储学生信息。
3. 定义了两个指向结构体的指针`p1`和`p2`,并将`p1`指向`stus1`数组的首元素,将`p2`指向`stus2`数组的首元素。
4. 使用`memcpy`函数将`stus1`数组中的数据复制到`stus2`数组中。
5. 使用指针遍历`stus2`数组,并输出每个学生的信息。
C语言创立一个结构体数组
以下是C语言创建结构体数组的示例代码:
```c
#include <stdio.h>
struct student {
char name[50];
int age;
float score;
};
int main() {
// 创建结构体数组
struct student stu_arr[3];
// 初始化结构体数组
strcpy(stu_arr[0].name, "Tom");
stu_arr[0].age = 18;
stu_arr[0].score = 90.5;
strcpy(stu_arr[1].name, "Jerry");
stu_arr[1].age = 19;
stu_arr[1].score = 88.5;
strcpy(stu_arr[2].name, "Mike");
stu_arr[2].age = 20;
stu_arr[2].score = 95.0;
// 遍历结构体数组并输出
for (int i = 0; i < 3; i++) {
printf("Name: %s, Age: %d, Score: %.1f\n", stu_arr[i].name, stu_arr[i].age, stu_arr[i].score);
}
return 0;
}
```