【问题标题】:Using malloc to allocate memory for an array使用 malloc 为数组分配内存
【发布时间】: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);

问题是我有一个函数可以将 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,但仍然遇到同样的错误。

【问题讨论】:

  • 你(没有)检查malloc()的返回值吗?
  • 请创建一个minimal reproducible example 来演示该问题。我想看看您如何将 Stud* 值传递给采用 Stud*[] 的函数。
  • new_student(Stud* students[], ... 等于 new_student(Stud** students, ...。但是你想要new_student(Stud* students,...。编译器应该已经警告过你了。
  • 好吧,我一定误解了你的意思,但你的回答似乎解决了我现在正在测试的问题。

标签: c arrays memory memory-management


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-12-13
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 2013-02-23
    • 2015-11-09
    • 2012-12-26
    相关资源
    最近更新 更多