-2

Does anybody see the bug here? I have got alternate solutions.

int main()
{

  char line[100], res[100], temp[20];
  fgets( line, 100*sizeof(char), stdin);    
  int i, j, l;
  for( i=strlen(line)-1; i>=0; i--)
  {
    if(line[i]==' ')
        for(j=i+1, l=0; line[j]!=' ' && line[j]!='\0'; l++, j++)
            temp[l]=line[j];
    temp[++l]=' ';
    temp[++l]='\0';
    strcat(res, temp);
  }
  puts(res);
  return 0;
}
Arun A S
  • 6,421
  • 4
  • 29
  • 43
  • 2
    Please tell us what behaviour you are actually seeing and how it differs from the expected behaviour. – ChrisF Apr 25 '15 at 17:20
  • Never do this `for( i=strlen(line)-1; i>=0; i--)`, you are computing the length of the string `length` of the string times, you should know that `strlen()` loops through the characters to count them. – Iharob Al Asimi Apr 25 '15 at 17:21
  • `strcat(res, temp);` - that isn't good. You never setup `res[]` as a terminated buffer, and `strcat` expects it to be so. So the hunt is on to find a `0` char, and if you're (un)lucky, you find one with enough space left over to actually concatenate your source string. – WhozCraig Apr 25 '15 at 17:26

2 Answers2

0

l and j are initialized just when line[i]==' '.

Witch won't be the case for the first iteration, where line[i] would be '\n'

Pedro Witzel
  • 368
  • 3
  • 14
0

The for and if loop are not required. Since the array follows 0 based indexing, i should take values from 0 to strlen(line)-1, so j=i+1 should be j=i (line 1). Strings should be null terminated - line 2. Also, l is already incremented in the for loop, so instead of pre-increment, use post-increment (or do not use it at all) (line 3).

#include<stdio.h>
#include<string.h>
int main()
{

 char line[100], res[100], temp[20];
 fgets( line, 100*sizeof(char), stdin);
 int i, j, l=0;
 res[0]='\0';   //line 2
 i=strlen(line)-1;

    for(j=i, l=0; line[j]!=' ' && line[j]!='\0'; l++, j--) //line 1
        {temp[l]=line[j];
         }
   temp[l++]=' ';   //line 3 (or temp[l]=' ')
   temp[l++]='\0';

   strcat(res, temp);

  puts(res);
  return 0;
}
Ayushi Jha
  • 4,003
  • 3
  • 26
  • 43