简体   繁体   English

使用malloc为数组分配内存

[英]Using malloc to allocate memory for an array

I'm trying to make an array of structs by using malloc to allocate the memory needed like so: 我试图通过使用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);

The problem is that I have a function that adds id and name to a place in the array like so: 问题是我有一个将idname添加到数组中某个位置的函数,如下所示:

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); 
}

But after the first call to the function, which works, the second one gives me the error: 但是在第一次调用该函数后,第二个函数给了我错误:

Segmentation fault (core dumped)

And I can only think that it must mean I'm not doing this right and all the memory is probably going into one place and not in an array form. 而且我只能认为这必须表示我没有正确执行此操作,所有内存可能都放在一个位置而不是数组形式。 I'd rather do 我宁愿做

  Stud students[STUDENT_SIZE];

but in this case I must use malloc. 但是在这种情况下,我必须使用malloc。

I tried using calloc but I still get the same error. 我尝试使用calloc,但仍然收到相同的错误。

There's a mismatch between the local variable Stud *students and the function parameter Stud *students[] . 局部变量Stud *students与功能参数Stud *students[]之间不匹配。 Those two variables ought to have the same type. 这两个变量应该具有相同的类型。

The local variable and malloc() look good. 局部变量和malloc()看起来不错。 new_student has an undesirable extra layer of pointers. new_student具有多余的指针层。 It should look like this instead: 它应该看起来像这样:

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); 
}

You would then call it like so: 然后,您可以这样称呼它:

Stud* students = malloc(sizeof(Stud)*STUDENT_SIZE);

new_student(students, 0);
new_student(students, 1);
new_student(students, 2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM