Possible Duplicate:
Getting Segmentation Fault
// reverse a string
#include`<stdlib.h>`
#include`<stdio.h>`
#include`<string.h>`
#include`<math.h>`
int main()
{
char *string = "mohit",t;
int i=0,j;
printf(" %d %d",strlen(string), (strlen(string)/2)+1);
for(i=0,j=(strlen(string)) ; i<(strlen(string)/2)+1 ; i++,j--)
{
printf("\n%d",(int) string);
printf("\n%d",(int) string+5);
printf("\ni string = %c", *(string + i));
printf("\nj string = %c", *(string + j));
t=*(string+i);
*(string+i) = *(string + j);
*(string + j) = t;
}
printf("\n = %s", string);
return 0;
}
String literals are possibly located in a read-only area of memory; it is not allowed to assign a pointer to one to a pointer to non-const char, and thus your manipulations of
stringcause undefined behaviour. You either sayand don’t modify the string, or you create an automatic array of chars that you can modify:
The latter is what you need in your case.
Also, as a point of style, writing
char * s, t;in one line is possibly misleading; it is equivalent to, and should always be replaced by,char * s; char t;.