Memory Allocation char* and char[]

前端 未结 3 510
天命终不由人
天命终不由人 2020-11-28 06:42

What is the difference between these two in terms of memory allocation.

char *p1 = \"hello\"; 
char p2[] = \"hello\";
相关标签:
3条回答
  • 2020-11-28 07:06

    Since the first one is a non-const pointer to const (read-only) data, the second is a non-const array, as Paul said, you can write:

    p2[2]='A'; //changing third character - okay
    

    But you cannot write:

    p1[2]='A';//changing third character - runtime error!
    
    0 讨论(0)
  • 2020-11-28 07:08

    The first one creates a pointer variable (four or eight bytes of storage depending on the platform) and stores a location of a string literal there, The second one creates an array of six characters (including zero string terminator byte) and copies the literal there.

    You should get a compiler warning on the first line since the literal is const.

    0 讨论(0)
  • 2020-11-28 07:10

    The first one is a non-const pointer to const (read-only) data, the second is a non-const array.

    0 讨论(0)
提交回复
热议问题