search

Home  >  Q&A  >  body text

c++ - char* p="123"这句代码为什么是对的?

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

迷茫迷茫2808 days ago1010

reply all(7)I'll reply

  • 伊谢尔伦

    伊谢尔伦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.

    reply
    0
  • PHPz

    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.

    reply
    0
  • PHPz

    PHPz2017-04-17 15:20:09

    Does

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

    reply
    0
  • ringa_lee

    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";
                   ^

    reply
    0
  • 大家讲道理

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

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 15:20:09

    The pitfalls left by C language

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 15:20:09

    This is left for compatibility with c

    reply
    0
  • Cancelreply