为什么';我的c代码不能使用指针和结构吗?
为什么不起作用?存在地址访问错误。然而,我试图在互联网和谷歌上找到这个问题,我做不到。我正在做我的作业。我的助手要求我们使用为什么';我的c代码不能使用指针和结构吗?,c,pointers,malloc,structure,C,Pointers,Malloc,Structure,为什么不起作用?存在地址访问错误。然而,我试图在互联网和谷歌上找到这个问题,我做不到。我正在做我的作业。我的助手要求我们使用 STUDENT ** list and Malloc () 然而,他们并没有很好地解释,所以我的日子不好过。我怎样才能解决这个问题?为什么我会出错?似乎要求您使用学生**列表,尽管这不是最好的方法。但鉴于这是一个练习,我将继续使用它,STUDENT**list将是指向该struct的指针数组 您的程序有两个主要错误 不为指针数组的每个元素分配内存 将输入数据分配到本
STUDENT ** list and Malloc ()
然而,他们并没有很好地解释,所以我的日子不好过。我怎样才能解决这个问题?为什么我会出错?似乎要求您使用学生**列表
,尽管这不是最好的方法。但鉴于这是一个练习,我将继续使用它,STUDENT**list
将是指向该struct
的指针数组
您的程序有两个主要错误
- 不为指针数组的每个元素分配内存
- 将输入数据分配到本地
,该结构在 函数退出结构
malloc返回的值
函数的结果(由scanf
返回的值)scanf
- 限制字符串输入溢出
内存使用后释放
#include <stdio.h>
#include <stdlib.h>
#define ID_LEN 7
#define NAME_LEN 10
typedef struct{
char id[ID_LEN];
char name[NAME_LEN];
int math;
int eng;
} STUDENT;
void SHOW(STUDENT* list) {
printf("ID : %s\n", list->id);
printf("name : %s\n", list->name);
printf("math : %d\n", list->math);
printf("eng : %d\n", list->eng);
}
void FirstList(STUDENT *list){
printf("ID : ");
scanf("%s", list->id); // use the pointer passed
printf("Name : "); // instead of local struct
scanf("%s", list->name);
printf("Math score: ");
scanf("%d",&list->math);
printf("English score: ");
scanf("%d",&list->eng);
}
int main(){
STUDENT **list = NULL;
int num = 0;
printf("How many student? ");
scanf("%d", &num);
list = malloc(num * sizeof(STUDENT*));
for(int i=0; i<num; i++) {
list[i] = malloc(sizeof(STUDENT)); // allocate memory for struct
FirstList(list[i]);
}
for(int i=0; i<num; i++) {
SHOW(list[i]);
}
return 0;
}
#包括
#包括
#定义ID_LEN 7
#定义名称\u LEN 10
类型定义结构{
字符id[id_LEN];
字符名[name_LEN];
整数数学;
国际工程;
}学生;
无效显示(学生*列表){
printf(“ID:%s\n”,列表->ID);
printf(“名称:%s\n”,列表->名称);
printf(“数学:%d\n”,列表->数学);
printf(“工程:%d\n”,列表->工程);
}
作废第一名单(学生*名单){
printf(“ID:”);
scanf(“%s”,list->id);//使用传递的指针
printf(“名称:”;//而不是本地结构
scanf(“%s”,列表->名称);
printf(“数学分数:”);
scanf(“%d”,&list->math);
printf(“英语分数:”);
scanf(“%d”,&list->eng);
}
int main(){
学生**列表=空;
int num=0;
printf(“多少学生?”);
scanf(“%d”和&num);
列表=malloc(num*sizeof(STUDENT*);
对于(int i=0;谢谢你的友好回答,我还有一个问题。那么我应该把免费()代码放在哪里?…你能再帮我一次吗?:)在程序结束时。您应该free
数组元素在循环中指向什么,然后是数组本身的free
——与对内存执行的malloc
操作相反。