[英]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.