c - realloc 不适用于二维指针数组

标签 c generics pointers realloc

在下面的代码中,我要求用户给我一些字符串。我制作了一个二维指针 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/

相关文章:

c - 使用 fgets 和 fscanf 时 C 中的段错误

c# - 方法和约束的唯一性

c# - Cast List<object> 和 Cast IEnumerable<object> 有什么区别

c# - 具有泛型和继承的编码风格

c - 将 regula falsi 方法修改为割线方法

求解稀疏方程组时的 csparse 误差

c - 链表函数返回中的指针问题我无法理解

c - 使用指针的 3d 数组

c - 返回具有多个可能值的 char 指针

c++ - 删除传递给构造函数的对象指针导致错误