Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, multidimensional array

When a multidimensional array is passed to a function, why does C++ require all but the first dimension to be specified in parameter li

like image 959
user1247347 Avatar asked Sep 03 '26 10:09

user1247347


1 Answers

A better way to ask this is to ask why C++ doesn't require the first dimension to be specified.

The reason is that for all arrays, you can't pass arrays by value to a function. If you try to declare a function taking an array the compiler will adjust the declaration to the corresponding pointer type.

This means that it doesn't matter what dimension you specify as the dimension doesn't form part of the function signature.

For example, these all declare exactly the same function.

void f(int *p);
void f(int p[]);
void f(int p[10]);
void f(int p[100]);

When navigating the array pointed to by p in the function, the only information that the copmiler needs is the size of the array elements, i.e. sizeof(int) in this case.

For more complex arrays exactly the same holds. These are all the same:

void g(Type p[][10][20]);
void g(Type (*p)[10][20]);
void g(Type p[10][10][20]);
void g(Type p[99][10][20]);

But these are all different from:

void g(Type p[][5][20]);

because adjusting the dimension of anything other than the outer array dimension affects the size of (at least) the outer array's elements meaning that the pointer arithmetic for navigating the array would have to change.

like image 155
CB Bailey Avatar answered Sep 06 '26 00:09

CB Bailey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!