Delhi
Delhi

Reputation: 51

typedef of a multidimensional array?

typedef int array [x][];

What does that means. What will happen if we have such a typedef. It was my interview question.

Upvotes: 5

Views: 5743

Answers (3)

Timothy Jones
Timothy Jones

Reputation: 22125

Let's assume you have somewhere:

#define x 3

As others point out, typedef int array [3][]; will not compile. You can only omit the most significant (ie first) element of an array length.

But you can say:

typedef int array [][3];

This means that array is an int array (of as-yet unspecified length) of length 3 arrays.

To use it, you need to specify the length. You can do this by using an initialiser like so:

array A = {{1,2,3,},{4,5,6}};   // A now has the dimensions [2][3]

But you CAN'T say:

array A; 

In this case, A's first dimension isn't specified, so the compiler doesn't know how much space to allocate for it.

Note that it's also fine to use this array type in a function definition - as arrays in function definitions are always converted to pointers to their first element by the compiler:

// these are all the same
void foo(array A);
void foo(int A[][3]);
void foo(int (*A)[3]); // this is the one the compiler will see

Note that in this case:

void foo(int A[10][3]); 

The compiler still sees

void foo(int (*A)[3]);

So, the 10 part of A[10][3] is ignored.

In summary:

typedef int array [3][]; // incomplete type, won't compile
typedef int array [][3]; // int array (of as-yet unspecified length) 
                         // of length 3 arrays

Upvotes: 8

user529758
user529758

Reputation:

You'll get a compilation error. For multidimensional arrays, at most the first dimension may be omitted. So for example, int array[][x] would be valid instead.

Upvotes: 3

ouah
ouah

Reputation: 145829

You'll get a diagnostic.

int [x][] is an incomplete array type that cannot be completed.

Upvotes: 1

Related Questions