在下面的代码中,我要求用户给我一些字符串。我制作了一个二维指针 char 数组,以便我使用指向长度为 50 的字符串的开头的指针字符串读取输入。我的问题是我在输入第一个字符串后一直崩溃......我假设我的问题与 realloc 有关。我不习惯..你能帮忙弄清楚发生了什么事吗??我尝试使用 netbeans 进行调试,但没有看到任何有趣的东西,因为它没有为 realloc 生成的新地址提供反馈!!
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char *str,**string,buffer[50],temp[2];
int i,j,q,size,counter;
size=10;
string=(char**) calloc(size,sizeof(char*));
for (i=0; i<size; i++) string[i]=(char*) malloc(50*sizeof(char));
printf("\nGimme strings, terminate input with x");
i=0;
gets(string[i]);
temp[0]=120;//x
temp[1]='\0';
size=0;
while(strcmp(string[i],temp)!=0)
{
string=realloc(string,size*sizeof(char**));
i++;
gets(string[i]);
size++;
counter++;
}
return 0;
}
我想用这个 realloc 使指针表更大。
最佳答案
string=realloc(string,size*sizeof(char**));
i++;
gets(string[i]);
size++;
在调用realloc
扩大string
后,新部分不包含任何有效指针。因此,当您调用 gets
时,您向它传递了一个您未能初始化的指针。
此外,size=0;
完全损坏了。
关于c - realloc 不适用于二维指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14236579/