C 二维字符数组内容被覆盖
我试图读取一个字符串并反转该字符串中的单词,但是字符串的内容被覆盖,并且我得到2D数组中前几个字符串的垃圾值。例如,当我在函数末尾以相反的顺序打印单词时,我的前几个字符串都是垃圾。我做错了什么C 二维字符数组内容被覆盖,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
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
s,即单个字符。你需要指针。因此,请使用以下命令:
words = realloc(words, word_count * sizeof(char*));
另外,如@所述,将单词
初始化为空
。否则,realloc
将尝试使用words
的未定义值作为内存进行重新分配。更多信息,请访问man realloc
注:
- 您应该
释放
使用后通过
返回给您的内存strdup
char
数组!请重新表述您的标题。此外,如果realloc
返回NULL
,则原始数组仍然被分配,并且您正在泄漏内存。由于这是一个运行时问题,请发布1)编译干净的代码,2)较小的代码3)显示问题。也就是说,需要添加#include语句和调用发布函数的main()函数。为保证健壮性,代码应检查s!=空值,这是!='\开始分析之前,请单击“0”。否则,发布的代码将失败。谢谢!出于某种原因,我认为我使用的是sizeof(char*)。现在工作!干杯不。规范的方法不是使用sizeof(type)
,而是使用sizeof*ptr\u to_realloc
,如words=realloc(words,word\u count*sizeof*words))
@LeelakrishnaN如果这解决了您的问题,您应该按下投票箭头下的复选标记,将其作为正确答案接受,切勿使用realloc()返回的值不必首先检查值是否为NULL。否则,指向某些已分配内存的原始指针将被NULL覆盖,从而导致内存泄漏