首页 文章

使用malloc为数组分配内存

提问于
浏览
0

我正在尝试通过使用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但我仍然得到同样的错误 .

1 回答

  • 4

    局部变量 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);
    

相关问题