well yes people you all were right. There is some error in the code
after fgets. What was happening was that the printf immediately after
fgets was also not getting executed because of some error further away
in my code. This was my first post so please don't castigate me for
this.
You didn't mention the call to change() between fgets() and printf()...
So here's a detailed explanation:
Basically what my code is supposed to do is accept a string from user
& reverse the position of the words, for e.g.
There are some problems with this code as others have said. Among other
things, limiting to only 20 words (a 50 character string could have up to 24
or so).
I put a version below that may or may not be helpful. There is no array of
pointers, but it does have to temporarily create a string the same size as
the input. But it has no other limits on string length or number of words.
Your input string has a \n at the end; where the string is unchanged (0 or 1
words) this \n stays.
The malloc allocation is a tight fit; an extra couple of bytes here won't
hurt.
/* reverse words in str in-place. separaters are spaces and tabs */
void change (char *str)
{
char *newstr;
char c, *p,*q, *r, *s;
int i,j,k,n,nwords;
if (str==NULL) return;
n=strlen(str);
if (n<=2) return; /* More than 2 words not possible, esp as last
char might be \n */
newstr=malloc(n+1); /* Build new string elsewhere */
if (newstr==NULL) return; /* Memory problem */
q=newstr; /* Point to start of dest string */
r=NULL; /* Point to last char of current word */
nwords=0;
for (p=str+n-1; p>=str; --p) {/* Scan source string starting from the end */
c=*p;
if (c==' ' || c=='\t' || c=='\n') {
if (r) { /* start of word encountered */
s=p+1;
for (i=0; i<(r-p); ++i) *q++ = *s++;
*q++=' ';
*q=0;
r=NULL;
++nwords;
}
}
else /* Assume c is part of word */
if (r==NULL) r=p; /* Remember last char of this word */
}
if (nwords) {
if (r) {
s=str;
for (i=0; i<(r-str+1); ++i) *q++ = *s++;
*q=0;
}
strcpy(str,newstr);
};
free(newstr);
return;
}