重新分配多维数组

时间:2013-08-12 15:29:01

标签: c arrays dynamic-memory-allocation

当我重新分配多维数组时,这是我的代码。当我多次使用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;
}

1 个答案:

答案 0 :(得分: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)。