簡體   English   中英

使用malloc為數組分配內存

[英]Using malloc to allocate memory for an array

我試圖通過使用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);

問題是我有一個將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); 
}

但是在第一次調用該函數后,第二個函數給了我錯誤:

Segmentation fault (core dumped)

而且我只能認為這必須表示我沒有正確執行此操作,所有內存可能都放在一個位置而不是數組形式。 我寧願做

  Stud students[STUDENT_SIZE];

但是在這種情況下,我必須使用malloc。

我嘗試使用calloc,但仍然收到相同的錯誤。

局部變量Stud *students與功能參數Stud *students[]之間不匹配。 這兩個變量應該具有相同的類型。

局部變量和malloc()看起來不錯。 new_student具有多余的指針層。 它應該看起來像這樣:

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

然后,您可以這樣稱呼它:

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