Home > Back-end >  Why do we have to use int a[][10] when passing 2d arrays to functions?
Why do we have to use int a[][10] when passing 2d arrays to functions?

Time:11-28

I want to pass a 2d array to a function, and I know how to do it

int function(int a[][10])

The problem is, I dont like working with stuff I dont understand, so I would like to understand why do we have to use "int a[][10]" instead of "int a[10][10]".

CodePudding user response:

First the function parameter a is a pointer to an array of size 10 having elements of type int. That is, the parameter a is not an array as you might be thinking.

This is called type decay as quoted below:

Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.

You asked

why do we have to use "int a[][10]" instead of "int a[10][10]".

It doesn't matter if you use int a[][10] or int a[10][10] because in both cases the parameter a is a pointer to an array of size 10 having elements of type int.

If you want to pass a 1D array of int elements you can use templates as shown below in version 1:

Version 1: Pass 1D array by reference


#include <iostream>

template<int N>
int function(int (&a)[N])// a is a reference to a 1D array of size N having elements of type int
{
    return 5; //return something according to your needs
}

int main()
{
    int arr[3] = {0};
    function(arr);
    return 0;
}

Version 2: Pass a 2D array by reference


#include <iostream>

template<int N, int M>
int function(int (&a)[N][M])// a is a reference to a 2D array
{
    return 5; //return something according to your needs
}

int main()
{
    int arr[10][10];
    function(arr);
    return 0;
}

  • Related