C语言怎么实现插入信息
时间: 2023-04-04 09:02:22 浏览: 54
C语言可以通过结构体和指针来实现插入信息。首先定义一个结构体,包含需要插入的信息,然后定义一个指针数组,用来存储结构体。接着,通过循环遍历指针数组,找到需要插入信息的位置,将后面的元素向后移动一位,最后将需要插入的信息插入到指定位置即可。具体实现可以参考以下代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
struct student {
char name[20];
int age;
float score;
};
int main() {
struct student stu[MAX_SIZE];
int n = 0; // 记录已有的学生数量
// 添加学生信息
strcpy(stu[0].name, "张三");
stu[0].age = 18;
stu[0].score = 90.5;
n++;
strcpy(stu[1].name, "李四");
stu[1].age = 19;
stu[1].score = 85.0;
n++;
// 插入学生信息
struct student new_stu;
strcpy(new_stu.name, "王五");
new_stu.age = 20;
new_stu.score = 92.0;
int insert_pos = 1; // 插入位置
for (int i = n; i > insert_pos; i--) {
stu[i] = stu[i - 1];
}
stu[insert_pos] = new_stu;
n++;
// 输出学生信息
for (int i = 0; i < n; i++) {
printf("姓名:%s,年龄:%d,成绩:%f\n", stu[i].name, stu[i].age, stu[i].score);
}
return 0;
}
```