NulledPointer NulledPointer - 1 year ago 64
C Question

2-D array with both bounds not specified

I looked at this SO post with no help.

int main()
int a[][] = {{1,2},{3,4}};


$ gcc a.c
a.c:6:8: error: array has incomplete element type 'int []'
int a[][] = {{1,2},{3,4}};
1 error generated.

Why is
incomplete type?

Why is
int a[][2]

I would've assumed that since compiler can initialize this 2-D array it can also figure out bounds automatically? I know that I'm required to provide size but why? Is it language requirement?

Answer Source

Here's the problem:

6.2.5 Types
An array type describes a contiguously allocated nonempty set of objects with a particular member object type, called the element type. The element type shall be complete whenever the array type is specified. Array types are characterized by their element type and by the number of elements in the array. An array type is said to be derived from its element type, and if its element type is T, the array type is sometimes called ‘‘array of T’’. The construction of an array type from an element type is called ‘‘array type derivation’’.

A 2D array is actually a 1D array where each element has array type. You can think of the declaration

T a[][N];

as having been written

typedef T R[N];
R a[];

Per the rule above, R must be a complete type; that means that if R is an array type, its size must be known. You could not write

typedef T R[];
R a[];

meaning you cannot write

T a[][];

This is irrespective of the presence of any initializer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download