简体   繁体   English

2D字符数组内容被覆盖

[英]2D character array contents getting overwritten

I am trying to read a string and reverse the words in the string., but the content of the strings is getting overwritten and I am getting garbage values for the first few strings in the 2D array. 我试图读取一个字符串并反转该字符串中的单词。但是,字符串的内容被覆盖,并且我正在获取2D数组中前几个字符串的垃圾值。 Eg when I print the words in reverse order at the end of the function, I am getting junk for the first few strings. 例如,当我在函数末尾以相反顺序打印单词时,前几个字符串会变得很乱。 What am I doing wrong? 我究竟做错了什么?

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--;
    }
}

You need to change that line: 您需要更改该行:

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

You allocate char s, that is, single characters. 您分配char ,即单个字符。 You want pointers. 您需要指针。 Therefore, use this: 因此,使用此:

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

Also, as @ Snild Dolkow stated, initialize words to NULL . 同样,如@ Snild Dolkow所述,将words初始化为NULL Otherwise realloc will attempt to use the undefined value of words as the memory to reallocate. 否则, realloc将尝试使用未定义的words值作为要重新分配的内存。 Further information at man realloc . 有关更多信息,请man realloc


Notes: 笔记:

  • You should free the memory returned to you by strdup after usage 使用后,应free strdup返回给您的内存

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM