Search code examples
cpointersmultidimensional-arrayincomplete-type

In C, what is the compatible incomplete pointer type of 3-dimensional array?


Suppose that we have a 2-dimensional array arr whose element type is int. Then we can define a compatible incomplete pointer type of arr: int (*p)[] = arr. However, if arr is 3-dimensional array, the similar definition int (*p)[][] = arr doesn't work because p is a pointer to an array with type of int [] which is an incomplete type in this case. How can I define the compatible incomplete pointer of a 3-dimensional array? Specifying the array size for last index such as int (*p)[][4] doesn't work for an array with different constant size or a variable length array (VLA).

In addition, I want to use this definition inside struct.


Solution

  • You can define array types with an unspecified number of elements (your int[]), but these are incomplete types. You cannot declare objects with such types. You can declare pointers to incomplete types (your int (*)[], or void *); these are complete types, but you cannot dereference them or perform pointer arithmetic with them. You cannot, however, define an array type with an incomplete element type. That is outside C's model for data types.

    In C, an n-dimensional array with n > 1 is an array of (n-1)-dimensional arrays. Since array element types must be complete, that means at most the first dimension of a multi-dimensional array type can be unspecified.

    As you observe, you can work around that to some extent by declaring pointers to incomplete array types, but to what end? The things you can do with such pointers are limited, to the extent that are few uses for them that are not served equally well by void *.