Arash Arash - 2 months ago 7
C Question

statements out of while loop does not run

I am practicing C by following code:

char* streverse(char* s){
int len=strlen(s);
int i=0; int j=len;
char* r;

while(i<j){
s[i]=s[j];
i++; j--;
}
printf("\nReverse string is %s",s);
return r;
}


But the printf never executes. If I remove the:

s[i]=s[j];


printf executes. This is strange because while loop ends anyway independent of above assignment. Any clues why printf doesn't execute with above assignment present?

EDIT:

By correcting the printf signature now it prints.

Answer

You should set j to len-1 as a first change, since otherwise you're accessing s outside its contents. More precisely, s[len] is going to be a NUL (or character \0), since that's how strings are stored in C. And it is going to be swapped with the first element of the s, effectively making it a zero-length string / empty string.

Second, the format should just be printf("\nReverse string is %s", s);

Also, you should assign r to something before returning it (to s probably?), otherwise it's just going to be initialised to gibberish and cause problems down the line when you try to use it as a pointer.