【问题标题】:Reallocating multidimensional array重新分配多维数组
【发布时间】:2013-08-12 15:29:00
【问题描述】:

这是我重新分配多维数组时的代码。当我多次使用函数 add_line 时,代码不起作用。一整天都想弄清楚。有人可以帮忙吗?

void add_line(char ** wlist, char * word, int * size) // Extending wordlist or cross
{
    (*size)++;
    char ** new_wlist = (char**)realloc(wlist,(*size)*sizeof(char*));
    if(new_wlist == NULL)
        show_error("Reallocation error",1);

    wlist = new_wlist;
    wlist[(*size)-1] = (char*)malloc(ROW_SIZE*sizeof(char));
     if(strlen(word)>ROW_SIZE)
        show_error("Word too long", 1);
    strcpy(wlist[(*size)-1],word);
}
int main()
{
    int * w_size = (int*)malloc(sizeof(int));
    int * c_size = (int*)malloc(sizeof(int));
    *w_size = 0;
     *c_size = 0;
    char ** wordlist = (char**)malloc(sizeof(char*));
    char ** cross = (char **)malloc(sizeof(char*)); 

    add_line(cross,"test1",c_size);
    add_line(cross,"test2",c_size);
    return 0;
}

【问题讨论】:

  • the code is not working 是什么意思?

标签: c arrays dynamic-memory-allocation


【解决方案1】:

问题是您没有返回修改后的wlist - 这是您的代码的固定(但未经测试)版本:

void add_line(char *** wlist, const char * word, int * size) // Extending wordlist or cross
              //   ^^^ note extra level of indirection here
{
    int new_size = *size + 1;
    char ** new_wlist = realloc(*wlist, new_size*sizeof(char*));
    if (new_wlist == NULL)
        show_error("Reallocation error",1);

    new_wlist[new_size-1] = malloc(ROW_SIZE);
    if (strlen(word)>ROW_SIZE)
        show_error("Word too long", 1);
    strcpy(new_wlist[new_size-1],word);
    *wlist = new_wlist;
    *size = new_size;
}

int main()
{
    int c_size = 0; // NB: no need for dynamic allocation here

    char ** cross = NULL; // NB: initial size is zero - realloc will do the right thing

    add_line(&cross, "test1", &c_size);
          // ^ pass pointer to cross here
    add_line(&cross, "test2", &c_size);
          // ^ pass pointer to cross here

    return 0;
}

我还修复了一些其他小问题 - cross 的初始大小现在是 0(它是 1),并且我已经删除了 c_size 的不必要的动态分配。我还删除了不必要的强制转换,这在 C 中可能很危险,并删除了 sizeof(char) 的冗余使用(根据定义等于 1)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-31
    • 2016-05-24
    • 2010-11-21
    • 1970-01-01
    • 2011-11-18
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多