二维字符数组内容被覆盖

时间:2015-08-26 18:23:08

标签: c

我正在尝试读取字符串并反转字符串中的单词。但是字符串的内容被覆盖了,我得到了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--;
    }
}

1 个答案:

答案 0 :(得分:3)

您需要更改该行:

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

您分配char s,即单个字符。你想要指针。因此,请使用:

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

此外,正如@ Snild Dolkow所述,将words初始化为NULL。否则realloc将尝试使用未定义的words值作为重新分配的内存。有关详情,请访问man realloc

注意:

  • 使用后free
  • 应该strdup内存返回给您