Realloc 2d char数组

时间:2018-05-04 07:44:33

标签: c multidimensional-array malloc realloc

我有一个2d动态分配的char数组,它应该保存从文件(stdin)到空格字符的字符串。由于我不知道文件中有多少字符串,因此我不断为2d数组重新分配更大的内存块,因此我有足够的空间来存储每个字符串。例如,如果我输入" hello world"作为该计划的输入,我希望' h'要打印出来,因为你好是第一个字符串,而h将是该字符串的第一个字符。

size_t size_buffer = 1;
char* buffer = (char*) malloc(size_buffer * sizeof(char)); //initial allocation that can hold 1 single char
size_t cur_nchars = 0; //number of characters read in current string

size_t size_words = 1; //initially only hold 1 string
char** words = (char**) malloc(size_words * sizeof(char*));
size_t cur_nwords = 0; //number of strings read

char read;
while ((read = getchar()) != EOF && !ferror(stdin)) {   
    if (read == ' ') { //space character
        //printf("reached a space character\n");
        words[cur_nwords] = buffer; //store string into words string array
        cur_nwords++; //increase number of words stored
        if (cur_nwords == size_words) { //maximum size hit
            size_words *= 2; //multiply old size by 2
            char** temp_words = (char**) realloc(words, size_words); //realloc new array twice as big

            if (!temp_words) {
                printf("can't allocate more memory");
                for (size_t i = 0; i < cur_nwords; ++i) {
                    free(words[i]);
                }
                free(words);
                exit(1);
            }
            else
                words = temp_words; //have old point to new
        }
        buffer = NULL;
        buffer = (char*)malloc(sizeof(char));
        cur_nchars = 0;
        continue;
    }
    if (cur_nchars == size_buffer) { //maximum length of string reached
        size_buffer *= 2; //new max length is doubled
        char* temp = realloc(buffer, size_buffer); //reallocate memory
        if (!temp) {
            printf("can't allocate more memory");
            free(buffer);
            exit(1);
        }
        else {
            buffer = temp; //set buffer to point to same location as temp
        }
    }
    buffer[cur_nchars] = read; //store character in char array
    cur_nchars++;   //increase # chars in string
}
printf("%c", words[0][0]); //throws error!

然而,在代码退出此循环后,2d数组字的内容似乎因某种原因被擦除(无法读取内存错误)...我有一种感觉,我不是正确地将内存重新分配给2d阵列。当我重新分配2d数组时,如果字符串本身的长度没有变化,我是否还需要重新分配char数组字符串?

0 个答案:

没有答案