/*Reverse all strings with pointers in str*/
#include <stdio.h>
#include <string.h>
int main()
{
char * str[] = {
"To err is human...",
"But to really mess things up...",
"One needs to know C!!"
};
void xstrrev(char *);
int i;
for(i=0;i<3;i++)
xstrrev(str[i]);
for(i=0;i<3;i++)
printf("%s\n", str[i]);
return(0);
}
void xstrrev(char * s)
{
int i = 0;
char str[strlen(s)+1];
while(*(s + i) != '\0')
{
str[i] = *(s + i);
i++;
}
str[i] = '\0';
i = 0;
while(*(s+i) != '\0')
{
//printf("%c\t%c\n", *(s + i), str[strlen(s) -i -1]);
*(s + i) = str[strlen(s) -i -1];
i++;
}
}
When I compile with gcc (version 4.8.2 ) and debug with gdb (version 7.7.1) I get
Starting program: /home/aditya/Documents/Programming/C/strrev
Program received signal SIGSEGV, Segmentation fault.
0x08048571 in xstrrev (s=0x8048620 "To err is human...") at strrev.c:39
39 *(s + i) = str[strlen(s) -i -1];
But I don't understand why. This has happened whenever I try to assign something using char pointers and while using array of pointers to strings. I tried uncommenting line the 5th last line and commenting the 4th last. I get the expected results without any error. Pls help.