views:

172

answers:

3

Possible Duplicate:
Why is this C code causing a segmentation fault?

char* string = "abcd";

now when i try to change some character of this string i get segmentation fault

*string = 'p';

or

string[0] = 'p';
string[0] = 52;

Can someone please explain me the reason that why is it happening.

Thanks

Alok.Kr.

+2  A: 

String literals are non-modifiable in C. This has been asked and answered many times before, though it isn't too easy to search for.

caf
That's why it's a good habit to write char const * p = "hello"rather than char * p = "hello"
bradgonesurfing
+4  A: 

If you write char* string = "abcd"; the string "abcd" is stocked into the static data part of your memory and you can't modify it.

And if ou write char* string = 'p';, that's just wrong. First, you try to declare a variable with the same name (string) and, worse, you try to assign a char value to a char pointer variable. This doesn't work. Same thing : char[0] = 'p'; really means nothing to your compiler except a syntax error.

Opera
sorry for all the typing errors, i guess i was so sleepy that i typed all those things.
Kumar Alok
Ok. So as I said "string[0] = 'p';" can't work because string is static data and is read-only.
Opera
+1  A: 

If you want to modify string, declare it as an array, not a pointer to a string literal.

#include <stdio.h>

int main()
{
    char string[] = "hello world";
    string[0] = 'H';
    string[6] = 'W';

    printf("%s\n", string);

    return 0;
}

Results in:

$ /tmp/hello
Hello World
bstpierre