如题,C风格字符串,"123"不是const char *类型的常量么?为什么赋给一个普通指针是可以的呢?
伊谢尔伦2017-04-17 15:20:09
Although no error will be reported by doing this, trying to modify the string 123
pointed to by p will cause a memory access violation. Because "123" is a string constant, stored in a read-only storage area. The reason why const char*
is required is to prevent programmers from mistakenly modifying 123
.
PHPz2017-04-17 15:20:09
Answers for Beginners
"123" is an object of const char type. const char * p should be read from right to left, which means that p is a pointer and the object pointed to is of type const char. This is not correct. What? In the same way, you are right to add p = "456"; at the end, as long as the object pointed to by p is const char.
ringa_lee2017-04-17 15:20:09
You will see a warning after compiling and adding -Wall
.
warning: ISO C++11 does not allow conversion from string literal to
'char *' [-Wwritable-strings]
char *p = "hello";
^
大家讲道理2017-04-17 15:20:09
char *p = "123"; It is actually two processes. Allocate string space in the constant area, declare the character pointer p, and p points to the memory space where the string is located. If there is anything wrong, please correct me immediately