2D char数组动态重定位失败

时间:2014-01-26 12:24:12

标签: c char dynamic-arrays

这是代码段。字典格式为:{word word \ n word word \ n ...}

该程序似乎在第二次重新分配2D数组roWords时失败了,我无法说明原因。

在声明中:char ** roWords = NULL,** enWords == NULL;

while (fgets(buffer, 100, dictionary))
    {
        counter++;

        roWords = (char**)realloc(roWords, sizeof(char*)* counter );
        enWords = (char**)realloc(enWords, sizeof(char*)* counter );

        p = strtok(buffer, " \n");


        roWords[counter - 1] = NULL;
        roWords[counter - 1] = (char*)realloc(roWords, sizeof(char)* strlen(p));
        strcpy(roWords[counter - 1], p);


        p = strtok(NULL, " \n");


        enWords[counter - 1] = NULL;
        enWords[counter - 1] = (char*)realloc(enWords, sizeof(char)* strlen(p));
        strcpy(enWords[counter - 1], p);


    }

1 个答案:

答案 0 :(得分:0)

解决方案是:

while (fgets(buffer, 100, dictionary))
{
    counter++;

    if (counter == 1)
    {
        roWords = (char**)malloc(sizeof(char*));
        enWords = (char**)malloc(sizeof(char*));
    }
    else
    {
        roWords = (char**)realloc(roWords, sizeof(char*)* counter);
        enWords = (char**)realloc(enWords, sizeof(char*)* counter);
    }

    p = strtok(buffer, " \n");


    roWords[counter - 1] = (char*)malloc(sizeof(char) * (strlen(p) + 1));
    strcpy(roWords[counter - 1], p);
    roWords[counter - 1][strlen(p)] = '\0';

    p = strtok(NULL, " \n");


    enWords[counter - 1] = (char*)malloc(sizeof(char)* (strlen(p) + 1));
    strcpy(enWords[counter - 1], p);
    enWords[counter - 1][strlen(p)] = '\0';

}