Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 943
Delhi Avatar asked Jan 08 '12 22:01

Delhi


1 Answers

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
like image 194
Timothy Jones Avatar answered Sep 29 '22 20:09

Timothy Jones