gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:33:44 24 4
gpt4 key购买 nike

我将要创建一个将学生数据存储在列表中的程序。我的问题是,我应该如何为我的结构数组中的每个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com