Possible Duplicate:
Why do I get a segmentation fault when writing to a string?
I want to write a function that reverses the given string passed into it. But, I can not. If I supply the doReverse function (see code below) with a character array, my code works well.
I can’t figure out why this does not work. I am able to access str[0] in doReverse, but I can’t change any value of the array by using a char pointer. Any ideas?
void doReverse(char *str) { str[0] = 'b'; } void main(void) { char *str = 'abc'; doReverse(str); puts(str); }
Update:
I know how to do write a reverse function by passing a character array to it:
void reverse1(char p[]) { int i, temp, y; for (i = 0, y = strlen(p); i < y; ++i, --y) { temp = p[y-1]; p[y-1] = p[i]; p[i] = temp; } }
But, I want to write another version that gets a char pointer as a parameter.
The simplest solution is to change the declaration of
strtoThis makes
stran array of char that is initialized to the string ‘abc’. Currently you havestras a pointer-to-char initialized to point to a string described by a string literal. There is a key difference: string literals are read-only to give the compiler maximum flexibility on where to store them; it is UB to modify them. But arrays of char are mutable, and so it’s okay to modify those.PS.
main()returns anint.