Possible Duplicate:
How to reverse a string in place in c using pointers?
I was trying to reverse a string using C.
A segmentation fault occurs. Any idea why?
Here’s my code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *str1 = "abbd";
char *str2;
str2 = str2 + strlen(str1)-1;
while(*str1 != '\0')
*(str2--) = *(str1++);
printf("%s", str2);
return 0;
}
Nothing’s properly allocated (allocate the proper length at declaration or malloc it) and you don’t really move through the strings and check for the end of your condition as fitted (try str[i]). You have awaken the kraken.