结构体建表
时间: 2023-08-01 20:06:31 浏览: 37
在C语言中,可以使用结构体来定义一张表。结构体是由多个数据类型组成的复合数据类型,可以自定义数据类型。下面是一个简单的例子:
```c
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
struct student {
char name[20];
int age;
float score;
};
int main() {
struct student table[MAX_SIZE];
int num = 0;
// 添加记录到表中
strcpy(table[num].name, "Tom");
table[num].age = 20;
table[num].score = 80.0;
num++;
strcpy(table[num].name, "Jerry");
table[num].age = 21;
table[num].score = 85.5;
num++;
// 输出表中的记录
for (int i = 0; i < num; i++) {
printf("name: %s, age: %d, score: %.2f\n", table[i].name, table[i].age, table[i].score);
}
return 0;
}
```
上面的代码中,我们定义了一个`struct student`结构体,包含了学生的姓名、年龄和分数。然后我们使用`table`数组来模拟一张表,通过添加记录和遍历表来演示表的操作。