【问题标题】:Trouble Resizing a 2D Array in C在 C 中调整二维数组的大小时遇到​​问题
【发布时间】:2013-10-26 17:18:48
【问题描述】:

我有一个项目,我在其中创建了一个 2D 字符数组来存储单词,可以选择添加更多单词,然后在必要时调整数组的大小。当我尝试使用它并修复它时,我遇到了各种错误,所以现在我认为我需要对我的代码多加注意。我专门寻找任何明显不正确或麻烦的分配内存或初始化数组的方式。

我得到的特定于此代码的错误是“free(): invalid pointer”并导致 SIGABRT。下面是我的代码。

这是我的调整大小功能。

char **  resize_array(char **array) 
{
int i;
char** tmp = malloc(2 * sizeof(*array));
int j;
for(j = 0; j < (2 * sizeof(*array)); j++)
    tmp[j] = malloc(2 * sizeof(*array));

for(i = 0; i < (sizeof *words); i++)
{
    strcpy(tmp[i], words[i]);
}

for(i = 0; words[i] != NULL; i++)
    free(words[i]);
free(words);
return tmp;
}

这是我正在实现的调整大小功能

            int len;
        len = (sizeof words);

    if(upperbound > len) //upperbound keeps track of the word count 
                                 //and resizes the array 
        { 
            char **tmp = resize_array((char **) words);
            int i;
            for(i = 0; i <= upperbound; i++)
                strcpy(words[i], tmp[i]);
        }

最后是最初初始化的“单词”数组。

    char words[14][50];

我正在使用 VI 并在 Ubuntu 上运行一切,仅供参考。提前感谢大家的帮助!

【问题讨论】:

  • 你不能调整数组的大小,你只能调整用malloc()动态分配的内存。
  • @Barmar,你是说我应该改变初始化单词数组的方式,否则我将无法“调整”它的大小?
  • 是的。你不能 free() 一些你一开始就没有 malloc() 的东西。

标签: c arrays multidimensional-array dynamic-arrays


【解决方案1】:

resize_array 函数中,您无法仅使用指向它的指针来确定数组的先前大小。

对 malloc 的调用

malloc(2 * sizeof(*array))

请求一个两倍于指向 char 的指针大小的分配(在 64 位机器上只有 16 个字节)。

这是您需要解决的第一个问题。

【讨论】:

    猜你喜欢
    • 2017-01-05
    • 2011-02-08
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多