Pass 2D Array to Function in C++

Two-dimensional arrays have rows and columns, storing data inside this matrix.

These 2D matrices cannot be passed directly to functions like single-dimension arrays. The program needs to follow some required rules.

Ways to Pass a 2D Array to function in C++

This article explains the various method to pass a 2D matrix to a method in C++.

Pass a 2D Array to a Function by Passing Its Pointer

By using a pointer, an array can be passed to the function if it has a variable size and if the size is known during the compile time.

Note: The first two programs deal with an array of varied sizes, which means the scope of these arrays is localized and needs to be declared more than once and the compiler has to check them for dimension mismatch.

The last program deals with an array of fixed sizes. These are declared only once in the program, eliminating the risk of dimension checks.

Let’s create a program that passes the array by passing its pointer.

  • Import package iostream and define namespace as std.

  • In this program, a function func is created having a single parameter – int(*array)[3][3] which is a pointer to a two-dimensional array having three rows and three columns each.

Note: An array is not a pointer, thus declaring it needs a little know-how for the programmer. The below ASCII diagram explains how the compiler differentiates between index and pointers.

Description of Array

The pointer to the entire array points to an array of six integers(depicted as a large box), whereas the pointer to the first element only points to a single integer (seen as a little box).

Despite being completely different types, a pointer to an object and a pointer to its first data member has the same value (the same location).

The parenthesis in the type int(*)[8] are vital if you are unfamiliar with the C declarator syntax:

  • A pointer to an array of 6 elements is denoted by – int(*array)[6].
  • 6 pointers of the type int* making up the array are denoted by – int* array[6].
  1. Inside the method, the contents of the array are printed using a for loop inside a while loop. The while loop iterates three times and for each iteration of i, the for loop iterates three times.

  2. Inside the main function, a two-dimensional array is created with the same dimension as the one in the func method. Then the array is initialized with key pair values.

  3. Lastly, the method is called by passing the pointer of the array to the method func().

When all of the array's dimensions are fixed and known at compile time, use this approach because the compiler flags dimensions in events of mismatch.

Complete code given below:

Output:

We have seen how the passing pointer of the array can pass an array to a function. In the next section, we will directly pass an array using a concept called decayed array pointers.

Pass an Array to the Function by Decaying the Pointer to the Array

Before venturing toward the program, let's first understand what is a decaying pointer.

An array type is represented as T[n], where T represents the element type and n represents the array's positive size, or the total number of elements, like:

The element type and size are products of the array type. Since the size is a component of the type, array types with different sizes are incompatible and unrelated to one another.

sizeof(T[n]) is equivalent to n * sizeof(T)

An array-like – int arr[5] represented in an ASCII diagram looks like this:

Description of a single array

Suppose two arrays T[m] and T[n] are created. The only "connection" between T[n] and T[m] is that both types can implicitly be transformed to T*, with the result being a pointer to the array's first element.

In other words, you can use a T[n] whenever a T* is needed, and the compiler will quietly provide that pointer.

This conversion, referred to as "array-to-pointer decay," removes the value inside the first index of the array, which stores the address. Since the array's size is no longer a component of the type (T*), it is lost during this procedure.

Decaying a pointer is useful when the programmer forgets the dimension and can decay it to point to its first element, but at the same time, its size is lost in the process.

This way an array can be directly passed to the function without the need to pass its address but doing so will force the compiler to decay it into a pointer and delete its 0th index. To combat it, we need to pass the number of rows as a separate argument.

Let's create a program that decays the array to pass its information.

  1. Import library package iostream and define the namspace as std.

  2. A function func_decay_pointer is created which has two parameters – a single pointer integer array arr of size – 4 and another variable rows of type – size_t.

    The reason to use a separate variable for rows instead of using a 2D array is that the compiler will decay the first index when this array will get passed. To avoid losing size, we store the size of rows separately.

    The declaration int(*arr)[4] can also be written as int array[][4]. Using the latter statement is legal but can confuse programmers as some may take it as a two-dimensional array whereas it is still a single-pointer integer array having 4 elements.

    This method provides some safety as passing an incorrect value of rows will cause the compiler to flag the values.

  3. Inside the method, the method name and the contents of the array are printed. Two nested for loops print the contents, where the first loop iterates up to the value of variable rows and the second loop iterates for the number of columns.

  4. Inside the main function, a two-dimensional array arr1 is created and initialized with some key pair values.

  5. Lastly, the function func_decay_pointer is called by passing the array and the value of row as an argument.

Output:

Pass a 2D Array to a Function in C++ Without Size by Passing Its Reference

This is the safest method to pass an array to a function but limits the flexibility of the operation. Having no size(fixed size) eliminates the risk of dimension mismatch and the dimensions are provided right at the compile time.

This program uses two individual variables for rows and columns of the 2D array and then uses those variables for the size of the array. The program does not lose its dimension because the reference of the array gets passed to the method.

The size of the array remains fixed throughout the program unlike the dynamic arrays, and thus does not requires the compiler to check for dimension mismatch.

Let's create a program that passes the array to its method by passing the reference.

  1. Two individual variables row and column of datatype – size_t are created inside a template.
  2. A method func_passby_refrnce is created having a dereferenced integer array &array as a single parameter with row and column as its dimensions.
  3. The name of the method and the contents of the array are printed using nested for loops, simmilar to what we did in previous program.
  4. Inside the main program, a two dimensional array of size [5][5] is created, and it's dimensions are initialized.
  5. Lastly, this array is passed to the function.

Output:

Conclusion

This article explains how to pass two dimensional array to a function using three different method. The reader after going through this article will easily create programs that pass two dimensional arrays to its methods.

It is hoped that this article helped in your learning journey.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *