c - 如何为结构数组中的 char 字符串分配内存?

标签 c arrays struct dynamic-memory-allocation

我将要创建一个将学生数据存储在列表中的程序。 我的问题是,我应该如何为我的结构数组中的每个 char 字符串分配内存。 我的代码在下面。如果还有其他错误,请指正。

#include <stdio.h>
#include <stdlib.h>
#define DATA 10;
#define NAME 10;

typedef struct{
int id;
char *givenname;
char *familyname;

} students;

int main()
{
int answer;
int incr = 0; // Index for students in the list
int datalen = DATA;
int namelen = NAME;

students *studentlist;
studentlist = malloc(datalen * sizeof(students)); // Allocate memory for first ten students

if(NULL == studentlist){
    printf("Error: Couldn't allocate memory\n");
    exit(0);
}

for(incr = 0; incr < datalen; incr ++){
    printf("Add student to the list? Yes(1) No(2)\n");
    scanf("%d", &answer);

    if(answer != 1){
        break;
    }

    studentlist[incr]->givenname = malloc(namelen * sizeof(char)); // Allocate memory for each name
    studentlist[incr]->familyname = malloc(namelen * sizeof(char));

    printf("Insert ID: ");
    scanf("%d", &studentlist[incr].id);

    printf("Insert given name: \n");
    scanf("%s", studentlist[incr].givenname);

    printf("Insert family name: \n");
    scanf("%s", studentlist[incr].familyname);


}

free(studentlist);
free(studentlist.givename);
free(studentlist.familyname);


return 0;
}

最佳答案

部分元素引用错误:

studentlist[incr]->givenname

应该是:

studentlist[incr].givenname

字符串的分配似乎没问题。

您的释放代码需要更改:

free(studentlist);
free(studentlist.givename);
free(studentlist.familyname);

您需要循环释放 studentlist.givename 和 studentlist.familyname,然后在最后释放 studentlist:

for(incr = 0; incr < datalen; incr ++){
   free(studentlist[incr].givename);
   free(studentlist[incr].familyname);
}
free(studentlist);

关于c - 如何为结构数组中的 char 字符串分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34144856/

相关文章:

c - 该程序中的 fgets

c - 如何正确地将 const char 数组分配给结构?

c++ - 数字时钟c++

javascript - 如何在调查中的地名数组中查找相同的字符串(使用javascript)

javascript - JS中如何使用流

c++ - 类 C 结构中自动字段重新排序的方法

c - 访问释放的指针,输出不应该是段错误吗?

c++ - 交换文件内容的有效方法

c - 如何使用C计算二维数组中的行数

java - java打印相同行和数组的方法问题