Search code examples
c++stringliteralsaccess-violationconst-cast

Referencing string with pointers


Possible Duplicate:
Why does simple C code receive segmentation fault?

Why code snippet 2 doesn't behave like snippet 1?

//Code snippet 1
char pstr[] = "helloworld";
char *p = pstr; 
p[2] = 'd';

//Code snippet 2
char *p = "helloworld";
p[2] = 'd'; //error: access violation

P.S Forgive my ignorance.


Solution

  • "helloworld" is an array of const char. There's a hole in the type system which allows you to point to it with a char*, because a lot of code exists which uses a char * to point to readonly data and this is safe.

    But const_cast rules apply, you can't actually write to the const data even if you make a non-const pointer to it.