0

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.

Community
  • 1
  • 1
Kumar Alok
  • 2,512
  • 8
  • 26
  • 36
  • http://stackoverflow.com/questions/3108832/write-permission-for-char – sinek Aug 03 '10 at 07:00
  • Also [Different string initialization yields different behavior?](http://stackoverflow.com/questions/1647273/different-string-initialization-yields-different-behavior) – caf Aug 03 '10 at 07:19
  • If this is only C, then remove the C++ tag, if this is C++, try avoiding names of types in the standard library as they might be confusing (i.e. do not call your strings `string`) – David Rodríguez - dribeas Aug 03 '10 at 07:41
  • "equate" is used incorrectly in the title. Variables are not "equated", they are assigned. – Olaf Seibert Jun 17 '15 at 14:48

3 Answers3

4

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
  • 983
  • 1
  • 6
  • 17
2

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
  • 233,326
  • 40
  • 323
  • 462
1

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
  • 30,042
  • 15
  • 70
  • 103