C++ Tutorial

The syntax of using a two-dimensional array & a one-dimensional array as a function parameter is different.

A one-dimensional array can be passed to a function as arguments (parameters) by passing it as a pointer & in addition, no extra mechanism needed.

ret_type func_name(int *arr)

or

ret_type func_name(int arr[])

 

But when it’s come to pass a 2D array(two-dimensional) as a function parameter, the syntax is different & difficult to remember.

Let’s look at following programs
Using Single Pointers
#include <iostream>
using namespace std;

void print(int *arr, int row, int col)
{
     for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            cout << *((arr + i * col) + j) << " " ;
         }
      }
}

int main()
{ 
    int arr[2][2] = { {1, 4},{ 2, 9} };

    print((int*)arr,2,2);
 
    return 0;
}

In this way, you can pass a two-dimensional array as a pointer. This is one is a little bit complex than the next one because in this way you have to type cast the array (pointer) address and calculate the sequential address of the 2D array to access the value in the function.

Using Convenient syntax

In the next program, you have to consider that

  • First array dimensionneed not be specified.
  • Second(any any further)dimension must be specified.
#include <iostream>
using namespace std;

void print(int arr[3][2], int row, int col)
{
     for (int i = 0; i < row; i++) {
         for (int j = 0; j < col; j++) {
             cout << arr[i][j] << " ";
 
         }
         cout << endl;
     }
}

int main()
{ 
    int arr[3][2] = { {1, 4},{ 2, 9}, {4, 5} };

    print(arr,3,2);
 
    return 0;
}

This one is more convenient & easy to remember but you’ve to remember to specify the second dimension or any further dimension when passing the array as a function argument.

Look at line 6, you will find that I’ve specified the first and second dimension respectively.

Rember, You may not specify the first dimension when passing an array dimension but be sure to pass the further dimension as the following prototype.

void print(int arr[][2], int row, int col);

 

Thank you very much for reading the article. Feel free to share your thoughts & ask any question regarding the article in the comment section.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.