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);
   else{
     temp[j] = '\0';
     count++;
     memptr = push(temp, memptr);
     j = 0;
   }
   k++;
  }
for(k = 0; k < count; k++)
  printf("%s\n", memptr[k]);

return 0;
}

Recommended Answers

All 2 Replies

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) != ' ' )

to

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.