簡體   English   中英

2D字符數組內容被覆蓋

[英]2D character array contents getting overwritten

我試圖讀取一個字符串並反轉該字符串中的單詞。但是,字符串的內容被覆蓋,並且我正在獲取2D數組中前幾個字符串的垃圾值。 例如,當我在函數末尾以相反順序打印單詞時,前幾個字符串會變得很亂。 我究竟做錯了什么?

void reverseWords(char *s) {
    char** words;
    int word_count = 0;

    /*Create an array of all the words that appear in the string*/
    const char *delim = " ";
    char *token;
    token = strtok(s, delim);
    while(token != NULL){
        word_count++;
        words = realloc(words, word_count * sizeof(char));
        if(words == NULL){
            printf("malloc failed\n");
            exit(0);
        }
        words[word_count - 1] = strdup(token);
        token = strtok(NULL, delim);
    }

    /*Traverse the list backwards and check the words*/
    int count = word_count;
    while(count > 0){
        printf("%d %s\n",count - 1, words[count - 1]);
        count--;
    }
}

您需要更改該行:

words = realloc(words, word_count * sizeof(char));

您分配char ,即單個字符。 您需要指針。 因此,使用此:

words = realloc(words, word_count * sizeof(char*));

同樣,如@ Snild Dolkow所述,將words初始化為NULL 否則, realloc將嘗試使用未定義的words值作為要重新分配的內存。 有關更多信息,請man realloc


筆記:

  • 使用后,應free strdup返回給您的內存

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM