C compound literals, pointer to arrays

前端 未结 5 1826
南笙
南笙 2020-12-13 13:12

I\'m trying to assign a compound literal to a variable, but it seems not to work, see:

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

I got a er

5条回答
  •  囚心锁ツ
    2020-12-13 13:52

    First understand that "Arrays are not pointers".

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

    In the above case p is an array of integers. Copying the elements {1,2,3,4,5,6} to p. Typecasting is not necessary here and both the rvalue and lvalue types match which is an integer array and so no error.

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

    "Note I don't understand why I got a error in the first one,.."

    In the above case, p an array of integer pointers. But the {{1,2,3},{4,5,6}} is a two dimensional array ( i.e., [][] ) and cannot be type casted to array of pointers. You need to initialize as -

    int p[][3] = { {1,2,3},{4,5,6} };
      // ^^ First index of array is optional because with each column having 3 elements
      // it is obvious that array has two rows which compiler can figure out.
    

    But why did this statement compile ?

    char *p[] = {"one", "two"...};
    

    String literals are different from integer literals. In this case also, p is an array of character pointers. When actually said "one", it can either be copied to an array or point to its location considering it as read only.

    char cpy[] = "one" ;
    cpy[0] = 't' ;  // Not a problem
    
    char *readOnly = "one" ;
    readOnly[0] = 't' ;  // Error because of copy of it is not made but pointing
                         // to a read only location.
    

    With string literals, either of the above case is possible. So, that is the reason the statement compiled. But -

    char *p[] = {"one", "two"...}; // All the string literals are stored in 
                                   // read only locations and at each of the array index 
                                   // stores the starting index of each string literal.
    

    I don't want to say how big is the array to the compiler.

    Dynamically allocating the memory using malloc is the solution.

    Hope it helps !

提交回复
热议问题