【发布时间】:2014-01-05 23:51:01
【问题描述】:
您好,我在大学的一个练习我需要用这种方式 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;
}
【问题讨论】:
-
不要投
mallocs. -
不要将
scanf与"%s"一起使用!请改用fgets或 POSIXgetline。只是出于好奇:你的大学有没有教过你像这样使用scanf? -
@mafso 是的...我们认为它等同于 fgets 或 getline