C compound literals, pointer to arrays

前端 未结 5 1843
南笙
南笙 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:58

    Since nobody's said it: If you want to have a pointer-to-2D-array, you can (probably) do something like

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

    EDIT: Or you can have a pointer to its first element via

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

    The reason why your example doesn't work is because {{1,2,3},{4,5,6}} is not a valid initializer for type int*[] (because {1,2,3} is not a valid initializer for int*). Note that it is not an int[2][3] — it's simply an invalid expression.

    The reason why it works for strings is because "one" is a valid initializer for char[] and char[N] (for some N>3). As an expression, it's approximately equivalent to (const char[]){'o','n','e','\0'} except the compiler doesn't complain too much when it loses constness.

    And yes, there's a big difference between an initializer and an expression. I'm pretty sure char s[] = (char[]){3,2,1,0}; is a compile error in C99 (and possibly C++ pre-0x). There are loads of other things too, but T foo = ...; is variable initialization, not assignment, even though they look similar. (They are especially different in C++, since the assignment operator is not called.)

    And the reason for the confusion with pointers:

    • Type T[] is implicitly converted to type T* (a pointer to its first element) when necessary.
    • T arg1[] in a function argument list actually means T * arg1. You cannot pass an array to a function for Various Reasons. It is not possible. If you try, you are actually passing a pointer-to-array. (You can, however, pass a struct containing a fixed-size array to a function.)
    • They both can be dereferenced and subscripted with identical (I think) semantics.

    EDIT: The observant might notice that my first example is roughly syntactically equivalent to int * p = &1;, which is invalid. This works in C99 because a compound literal inside a function "has automatic storage duration associated with the enclosing block" (ISO/IEC 9899:TC3).

提交回复
热议问题