Difference between 2d array passing and 1d array passing

Why when passing 2d arrays to functions let's say that's the func
int foo(int a[5][5])

and if I pass an array of [10][10] it would give me an error

BUT

if int foo(int a[5])
I could pass anything from 1 to max array size and it'd still work.

Why is that?
When passing an array to a function you are actually passing a pointer to the first element in the array.

All of the following have the exact same meaning.
1
2
3
int foo(int a[5])
int foo(int a[])
int foo(int* a)

A pointer to the first element in the array and the size of each element is all that is needed in order to work out the memory location of an array element using an index.

ArrayElementAtIndex = addressOfFirstElement + sizeOfArrayElement * index


A 2D array is an array of arrays (i.e. each array element is an array of fixed size). In your example each array element is an int array of size 5. As I said above the compiler needs to know the size of the array elements so you cannot leave out the size of the int arrays, but you can leave out the first dimension that specifies how many int arrays there are.

All of the following have the exact same meaning.
1
2
3
int foo(int a[5][5])
int foo(int a[][5])
int foo(int(*a)[5])
Last edited on
Thanks <3
Topic archived. No new replies allowed.