【发布时间】:2016-12-14 17:43:26
【问题描述】:
我正在尝试通过使用 malloc 来创建一个结构数组来分配所需的内存,如下所示:
typedef struct stud{
char stud_id[MAX_STR_LEN];
char stud_name[MAX_STR_LEN];
Grade* grd_list;
Income* inc_list;
}Stud;
Stud* students = malloc(sizeof(Stud)*STUDENT_SIZE);
问题是我有一个函数可以将 id 和 name 添加到数组中的某个位置,如下所示:
void new_student(Stud* students[], int stud_loc){
scanf("%s", students[stud_loc]->stud_id);
printf("%s", students[stud_loc]->stud_id);
scanf("%s", students[stud_loc]->stud_name);
printf("%s", students[stud_loc]->stud_name);
}
但在第一次调用该函数后,第二个函数给了我错误:
Segmentation fault (core dumped)
而且我只能认为这一定意味着我没有正确执行此操作,并且所有内存可能都进入一个位置而不是数组形式。我宁愿做
Stud students[STUDENT_SIZE];
但在这种情况下我必须使用 malloc。
我尝试使用 calloc,但仍然遇到同样的错误。
【问题讨论】:
-
你(没有)检查
malloc()的返回值吗? -
请创建一个minimal reproducible example 来演示该问题。我想看看您如何将
Stud*值传递给采用Stud*[]的函数。 -
new_student(Stud* students[], ...等于new_student(Stud** students, ...。但是你想要new_student(Stud* students,...。编译器应该已经警告过你了。 -
好吧,我一定误解了你的意思,但你的回答似乎解决了我现在正在测试的问题。
标签: c arrays memory memory-management