[英]Reallocating char** array in c (Seg fault core dumped)
I m reallocating a char**
array with every entry and while compiling comes back clean, only the first entry is stored and I get Segmentation fault (core dumped) always when i try to register a 4th entry. 我为每个条目重新分配一个
char**
数组,并且在编译返回干净时,仅存储第一个条目,并且总是在我尝试注册第四个条目时遇到Segmentation Fault(核心转储)。
Here is the relevant code in main.c: 这是main.c中的相关代码:
int main(int argc, char *argv[])
{
int i,sizea,sizeb,choice,letters,check,mistakes,count;
char C[26][2];
char **A,**B,a;
A=(char**)malloc(sizeof(char*));
*A=(char*)malloc((MAX_CHAR+1)*sizeof(char));
sizea=1;
build(&A,&sizea);
return 0;
}
And here is the implementation of the method in mylib.c: 这是mylib.c中方法的实现:
void build(char ***A, int *sizea)
{
*A=(char**)realloc(*A,(*sizea) * sizeof(char*));
*A[*sizea-1]=(char*)malloc((MAX_CHAR+1)*sizeof(char));
printf("Give word :");
scanf("%s",(*A[*sizea-1]));
(*sizea)++;
}
Thanks a lot for your help. 非常感谢你的帮助。
edit: similar problems in this method that werent fixed by doing the same thing 编辑:这种方法中的类似问题,无法通过做相同的事情来解决
void find(char **A, char ***B, int letters,int sizea, int *sizeb){
int i,j,k,dummy;
char a='a';
for(i=0;i<(sizea-1);i++){
printf("here\n");
if(A[i][letters]=='\0'){
*B=(char**)realloc(*B,(*sizeb+1) * sizeof(char*));
(*B)[*sizeb]=(char*)malloc((letters+1)*sizeof(char));
(*B)[*sizeb-1]=A[i];
*sizeb++;
printf("%s\n", (*B)[i]);
}
}
}
The problem is here: 问题在这里:
scanf("%s",(*A[*sizea-1]));
The array index operator []
has higher precedence than the dereference operator *
. 数组索引运算符
[]
优先级高于取消引用运算符*
优先级。 So the above parses as: 因此,上面的解析为:
scanf("%s",(*(A[*sizea-1])));
What you want is: 您想要的是:
scanf("%s",((*A)[*sizea-1]));
Similarly, this: 同样,这:
*A[*sizea-1]=(char*)malloc((MAX_CHAR+1)*sizeof(char));
Should be: 应该:
(*A)[*sizea-1]=(char*)malloc((MAX_CHAR+1)*sizeof(char));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.