gpt4 book ai didi

c - 动态数组重新分配

转载 作者:行者123 更新时间:2023-11-30 19:03:09 25 4
gpt4 key购买 nike

我正在尝试创建一个动态列表,但由于某种原因该列表的元素数量不会超过 2

    typedef struct{
char* name;
int age;
} student;

int Insert(void){
int const MAX = 1000;
int age;
char name[MAX];
int i=1;
int const ENOGH = 2;
int const AGE_ERR = 1;
int flag=0;

student** array = NULL;
do{
printf("insert student name\n");
printf("user: ");
scanf("%s",name);
if( strcmp(name,"enough") != 0){
printf("insert age\n");
printf("user: ");
scanf("%d",&age);
}else{
return ENOGH;
}
if ( age == -1){
flag = AGE_ERR;
}
if (age != AGE_ERR){
array = realloc(array, sizeof(student*)*(i+1));
array[i] = malloc(sizeof(student));
if (array[i] == NULL){
printf("Erorr\n");
}
array[i]->name =(char*)malloc(sizeof(char)*(strlen(name)+1));
strcpy(array[i]->name ,name);
array[i]->age = age;
i++;
}
}while (flag != AGE_ERR);

return AGE_ERR;
}

我确信它与列表指针的重新分配和列表元素分配有关,但我找不到什么

(while 循环永远不会结束以保存一些代码)

最佳答案

这是不正确的:

 array[i]->name =(char*)malloc(sizeof(strlen(name)));

strlen 函数返回一个 int,因此 sizeof(strlen(name)) 计算结果为 int< 的大小。对于您存储的任何字符串来说,这很可能都不够长。

您想要:

 array[i]->name = malloc(strlen(name) + 1));

这为字符串加上终止空字节分配空间。实际上,您可以通过调用 strdup 来替换此行及其后面的 strcpy:

 array[i]->name = strdup(name);

关于c - 动态数组重新分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54522244/

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