c++ - char* p="123"这句代码为什么是对的?
迷茫
迷茫 2017-04-17 15:18:09
0
7
1005

如题,C风格字符串,"123"不是const char *类型的常量么?为什么赋给一个普通指针是可以的呢?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(7)
伊谢尔伦

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.

PHPzhong

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.

PHPzhong

Does

char *p = "123"; represent a character array? That is string

左手右手慢动作

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";
               ^
大家讲道理

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

巴扎黑

The pitfalls left by C language

左手右手慢动作

This is left for compatibility with c

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template