https://www.barbieinablender.org/

### Archive

Posts Tagged ‘2D Arrays’

## Passing 2D Arrays to functions

Passing 2D arrays without bounds is a common error people make.
Some people assume that if this works:

`void someFunc(int []);`

then this should should work too:

`void anotherFunc(int [][]);`

As normal as it may seem, it is incorrect.

For passing 2D Arrays to a function, the column element must be mentioned like this:

`void func1(int [][upperSize]);`

But why do we need to include the column element? If C/C++ compilers can figure out the size of a 1D array then why not for 2D?

That’s because 2D Array elements are stored consecutively as two 1D Arrays.

Have a look at this code snippet:

```int main()
{
int x[]={1,2,3,4,5,6,7,8,9,10};
int *p,*q;
int i;
p=&x;
for(i=0;i<10;i++)
printf(”%d “,*(p+i));

printf(”nn Now using pointer q:n”);

q=&x;
for(i=0;i<10;i++)
printf(”%d “,*(q+i));

return 0;
}```

Run the Program. You’ll get this as the output.
`1 2 3 4 5 6 7 8 9 10`

``` ```

```Now using pointer q: 3 4 5 6 7 8 9 10 0 4239532```
Now change the number 2 in the array declaration to 5 like this:

`int x[]={1,2,3,4,5,6,7,8,9,10};`

Run the code and observe the output:
`1 2 3 4 5 6 7 8 9 10`

``` ```

```Now using pointer q: 6 7 8 9 10 0 4239532 0 4235541 1```

As you can see, the output using the pointer p remains unchanged because we’re setting it to the first element of the array itself, so it iterates to every element after it.

But q is set to the first element of the 2nd row.
Now which one is the first element of the second row? It’s 6. How do we know it?
It’s because we’ve placed 5 in the column bracket to specify the bounds of each column.

So if we don’t place any value, the compiler gets confused as to how many numbers can be grouped into one column.
Hence whenever such confusion occurs, the compiler generates the error: size of the int[] is unknown or zero.

Categories: Programming Tags: