c语言在3行4列的二维数组储存学生名字,学号,分数,怎样在数组添加新学生的信息,数组还不知道要多少行
时间: 2024-03-24 20:41:17 浏览: 19
如果数组还不知道要多少行,则可以使用动态内存分配来解决。下面是一个示例代码,用来向二维数组中添加新学生:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ROWS 3
#define COLS 4
int main() {
// 动态分配二维数组内存
char **studentInfo = (char **)malloc(sizeof(char *) * ROWS);
for (int i = 0; i < ROWS; i++) {
studentInfo[i] = (char *)malloc(sizeof(char) * 20);
}
// 向数组中添加学生信息
int curRow = 0;
char name[20], id[10], score[10];
while (1) {
printf("请输入第%d个学生的信息(姓名 学号 分数):", curRow+1);
scanf("%s %s %s", name, id, score);
if (strcmp(name, "exit") == 0) { // 如果输入exit,则结束输入
break;
}
// 如果行数已经达到上限,则重新分配内存
if (curRow == ROWS) {
ROWS += 1;
studentInfo = (char **)realloc(studentInfo, sizeof(char *) * ROWS);
studentInfo[ROWS-1] = (char *)malloc(sizeof(char) * 20);
}
// 添加学生信息到数组中
strcpy(studentInfo[curRow][0], name);
strcpy(studentInfo[curRow][1], id);
strcpy(studentInfo[curRow][2], score);
curRow++;
}
// 打印输出学生信息
printf("学生信息如下:\n");
for (int i = 0; i < curRow; i++) {
printf("%s %s %s\n", studentInfo[i][0], studentInfo[i][1], studentInfo[i][2]);
}
// 释放内存
for (int i = 0; i < ROWS; i++) {
free(studentInfo[i]);
}
free(studentInfo);
return 0;
}
```
该代码使用了动态内存分配来动态地创建二维字符数组`studentInfo`,并通过循环向数组中添加学生信息。在循环过程中,如果行数已经达到上限,则使用`realloc`函数重新分配内存,以扩充数组的行数。最后,我们通过循环打印输出学生信息,并在程序结束前释放内存。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)