Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why a "char*" can point to a "const char*"?

Tags:

c

char

constants

the following code can be compiled correctly on both VC or gcc:

char *str = "I am a const!";
str[2] = 'n';

however, obviously there is a run-time-error. Since "I am a const!" is a const char*, why the compiler doesn't give an error or even a warning ??


Besides, if I define char a[] = "I am const!", all the elements in a can be modified, why this time the string literals become nonconst ?

like image 715
Flybywind Avatar asked Oct 02 '11 03:10

Flybywind


1 Answers

As far as C is concerned, that string literal is not const, it's a char[14] which you assign to a char*, which is perfectly fine.

However, C does say that changing a string literal is undefined behavior.

like image 119
nos Avatar answered Oct 20 '22 01:10

nos