c - 二维字符数组内容被覆盖

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

最佳答案

您需要更改该行:

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

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

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

另外,如@Snild Dolkow声明,将words初始化为NULL。否则,realloc 将尝试使用 words 的未定义值作为要重新分配的内存。更多信息请参见 man realloc

<小时/>

注释:

  • 您应该在使用后释放strdup返回给您的内存

关于c - 二维字符数组内容被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32233990/

相关文章:

c - c中函数和main之间的变量

c - 在处理庞大的管道数据时需要建议

c - 比较c中的两个char指针值时strcmp返回true

java - 对于没有保证析构函数的语言,涉及非 gced 内存的语言绑定(bind)?

c - 为了使 SetSecurityDescriptorGroup 不失败,需要对我的代码进行哪些修改?

地穴(): Pointer to integer without cast?

Android NDK套接字创建空指针

linux内核频繁分配大内存选择内存分配api

c - 使用 ualarm 的问题

c - fclose() 有什么意义?