gpt4 book ai didi

c - Malloc 重新分配免费

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:53 25 4
gpt4 key购买 nike

你好,我在大学做一个练习,我需要用这种方式 malloc 一个数组。 stars 的数组有 1 个槽。如果输入多于一个,则数组加倍。如果输入超过 2,那么它会再次加倍等。在此之后,我必须裁剪数组以适应输入的数量。例如,如果我有 5 个输入,那么数组将有 8 个槽,我必须让它有 5 个槽,但我不知道该怎么做。到目前为止,这是我的代码:

nameInfoT* ReadNames(int* size){
nameInfoT* names ;
int array_size=1;
int entries=0;
char input[length];
names=(nameInfoT*) malloc(sizeof(nameInfoT)*array_size);

do{
scanf("%s",input);
if(!strcmp(input,"END")) break;

if(entries==array_size){
array_size=array_size*2;
names= (nameInfoT*) realloc(names,sizeof(nameInfoT)*array_size);
}

names[entries].name=(char*)malloc(sizeof(char)*strlen(input));
strcpy(names[entries].name,input);

entries++;

}while(1);

printf("there are %d free spaces \n",array_size-entries);
*size=entries;
printf("there are %d entries \n",*size);

int i;
for(i=array_size;i>entries;i--){
free(names[i]);//here it won't compile
}
return names;

}

最佳答案

您只能free malloc/calloc/realloc 的结果。您不能释放单个元素。所以最后你可以简单地 realloc 再次达到所需的最终大小。

关于c - Malloc 重新分配免费,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20940773/

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