Can you please explain the reason of the garbage output instead of the each words in the string..

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int count = 0;
//char** memptr = NULL;

char** push(char* word, char** memptr){
 if(count > 1)
     memptr = (char**)realloc(memptr, (count * sizeof(char*)) ); 
 memptr[count - 1] = (char* )malloc(strlen(word));
 strcpy(memptr[count - 1], word);
return memptr;

int main(){
  char string[] = "World has changed your thoughts";
  int k = 0, j = 0;
  char temp[strlen(string)];
  char** memptr = (char**)malloc(sizeof(char *));
  while(*(string + k)){
   printf("%s", temp);
   if(*(string + k) != ' ' )
      temp[j++] = *(string + k);
     temp[j] = '\0';
     memptr = push(temp, memptr);
     j = 0;
for(k = 0; k < count; k++)
  printf("%s\n", memptr[k]);

return 0;
3 Years
Discussion Span
Last Post by JohnMcPherson

sorry guys, I asked the wrong question..This is actually working properly but the last word is not printed..the reason is that it is not encountering any space after the last word & hence the push funtion is never called from the else part..So please tell me the way to solve this..


Since you have two conditions that signal the end of a word, a space or the null terminator of the string, your if statement has to check for both of those conditions. In other words, you need to change the if from

if(*(string + k) != ' ' )


if(((string + k) != ' ' ) && ((string + k) != '\0' ))

With this if statement, when you reach the end of the last word in the string, it will encounter the null terminator, and the else, with the push, will execute.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.