C: Behaviour of arrays when assigned to pointers

前端 未结 4 1566
名媛妹妹
名媛妹妹 2021-01-27 20:17
#include 

main()
{
  char * ptr;

  ptr = \"hello\";


  printf(\"%p %s\" ,\"hello\",ptr );

  getchar();

}

Hi, I am trying to underst

4条回答
  •  忘掉有多难
    2021-01-27 21:03

    "hello" is a string literal. It is a nameless non-modifiable object of type char [6]. It is an array, and it behaves the same way any other array does. The fact that it is nameless does not really change anything. You can use it with [] operator for example, as in "hello"[3] and so on. Just like any other array, it can and will decay to pointer in most contexts.

    You cannot modify the contents of a string literal because it is non-modifiable by definition. It can be physically stored in read-only memory. It can overlap other string literals, if they contain common sub-sequences of characters.

    Similar functionality exists for other array types through compound literal syntax

    int *p = (int []) { 1, 2, 3, 4, 5 };
    

    In this case the right-hand side is a nameless object of type int [5], which decays to int * pointer. Compound literals are modifiable though, meaning that you can do p[3] = 8 and thus replace 4 with 8.

    You can also use compound literal syntax with char arrays and do

    char *p = (char []) { "hello" };
    

    In this case the right-hand side is a modifiable nameless object of type char [6].

提交回复
热议问题