0

In passing a 2-D array in functions, why are we giving its column number as follows:

int arr1[2][3] = {{1,2,3}, {4,5}};

void Array(const int [][3]); // prototype

Why we have to pass it column width? If i keep it empty it gives an error!

Cory Kramer
  • 98,167
  • 13
  • 130
  • 181
Mark
  • 21
  • 5

2 Answers2

3

A two dimensional array is in fact a one-dimensional array elements of which are in turn one dimensional arrays.

You can consider an array declaration like this

int arr1[2][3] = {{1,2,3},{4,5}};

the following way

typedef int T[3];
T arr1[2] = {{1,2,3},{4,5}};

When you pass an array by value as an argument to a function it is converted to pointer to its first element.

So if you have a function like this

void Array(const T arr[] );

then this declaration is equivalent to

void Array(const T *arr );

and the both declare the same one function.

It is important to know the complete type T that you can use the pointer arithmetic with the pointer. For example when you use expression ++arr then it means that the current value in arr is increased by sizeof( T ). So the compiler need to know sizeof( T ). Otherwise it will be unable to do the pointer arithmetic.

So returning to your example the compiler need to know the type of element of the two dimensional array that is that its type T is int[3]

So this decleration

void Array(const int [][3]); 

is equivalent to

void Array(const int ( * )[3]); 

or to the following

typedef int T[3];
void Array(const T * );

In this case the compiler will know the size of the object (the first element of the passed array) pointed to by its parameter that is by the pointer.

Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268
0

One thing I noticed is that this initialization looks supicious:

int arr1[2][3] = {{1,2,3}, {4,5}};

arr1 has 2 rows and columns. Why is there no initialization of the 3rd column of row 2? (FYI the compiler will make it zero, but I'm not sure if that was the intent.)

In C, a multidimensional array is represented as a "flattened" 1 dimensional array. This is explained here: How Are C Arrays Represented In Memory?

In a 2 dimensional array the elements are stored in row major order. So these 2 declarations are conceptually the same:

int arr2[ROWS][COLS];
int arr1[ROWS*COLS];

And these 2 accesses are conceptually the same:

arr2[i][j]
arr1[(i*COLS)+j]

In in fact, in C, the second form is what's happening under the hood. This explains why your prototype needs to know how many columns - it's so the compiler can perform the multiplication to get the proper element in the linear array.

Community
  • 1
  • 1
Ron Kuper
  • 797
  • 3
  • 14