我有一个结构国家和一个结构体数组。我重新分配,但结构成员中有一个我无法理解的问题。这是代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct country{
char* name;
char* col;
int num;
char** nb;
struct country* add;
};
int main(void){
int ch, i = 0;
struct country* A = (struct country*)malloc(sizeof(struct country));
while(1){
/*allocation for colour, name, */
A[i].col = (char*)malloc(16*sizeof(char));
A[i].name = (char*)malloc(16*sizeof(char)); /* BBBBUUUGGG HEEEERRRRREEEE <<<<<<<<<<<<<<<<_________-----------------____________________---------------------*/
A[i].nb = (char**)malloc(sizeof(char*));
A[i].nb[0] = (char*)malloc(sizeof(char));
A[i].num = 0; /* define number of countries and then increase it*/
scanf("%s %s", A[i].col, A[i].name); /*value for colour, name of current country(node)*/
ch = getchar(); /* see if there are neighbors or next country or the end*/
while((ch=='\t') || (ch==' ')){ /* whitespace or tab means neighbor */
A[i].nb = (char**)realloc(A[i].nb, (A[i].num+1)*sizeof(char*)); /* increase the elements of array(names of neighbors) by one */
A[i].nb[A[i].num] = (char*)malloc(16*sizeof(char)); /* allocate memory for the name of the next neighbor(he is the num'th neighbor)*/
scanf("%s", A[i].nb[A[i].num]);
(A[i].num)++;
ch = getchar();
}
(A[i].num)--; /*we have increased the number of neighbors one time more than the actal size */
if(ch!=EOF){ /* means that we have another line and so another country */
A = (struct country*)realloc(A, (i+1)*sizeof(struct country)); /* another country-->A should be bigger */
i++;
}else{
break; /* END OF FILE no more countries*/
}
}
}
name ==国家名称,col =县的颜色,num =国家的邻居数,并且** nb是具有其名称的数组,忽略struct countr * add
您遇到的一个问题是如何增加A
数组的大小(使用i
变量!!
使用此代码:
if(ch!=EOF){ /* means that we have another line and so another country */
A = (struct country*)realloc(A, (i+1)*sizeof(struct country)); /* another country-->A should be bigger */
i++;
}else{
break; /* END OF FILE no more countries*/
}
您有一个“ off-by-one”错误!
因此,在第一次执行while
循环时,i
的值为零,因此您的realloc
调用将创建一个新的缓冲区,足以容纳just one结构(i + 1
)-但您已经有一个这样的结构的缓冲区!
解决方案:您需要将i++
行放在之前 realloc
调用!
编辑:您在内部while
循环中使用此行有一个非常相似的问题:
A[i].nb = (char**)realloc(A[i].nb, (A[i].num+1)*sizeof(char*));
但是在此之前,最好先使用(A[i].num+2)
修复它,因为在增加它之前,多次使用(正确)A[i].num
值。