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. 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. You want pointers. Therefore, use this:
words = realloc(words, word_count * sizeof(char*));
Also, as @ Snild Dolkow stated, initialize words
to NULL
. Otherwise realloc
will attempt to use the undefined value of words
as the memory to reallocate. Further information at man realloc
.
Notes:
free
the memory returned to you by strdup
after usage
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.