Chinmay Vemuri
Chinmay Vemuri

Reputation: 199

Issue in Passing a 2-D array

I read how to pass 2-D arrays in a function as a parameter and tried to implement the same. There are two problems which I encountered:

1) The first line of the output of the code contains garbage value. 2) What does the line ((arr + in) + j) actually do ? I mean, Why can't we do something like ((arr + i) + j) to access arr[i][j] ?

I also tried passing the matrix using parameter int **arr and then tried printing the value as arr[i][j] but there was no output.

Here is the output that I get:-

Enter number of nodes: 4
0167772161878012032-1
0000
0000
0000

And here is my code :-

#include <iostream>
using namespace std;

void show(int* arr, int n)
{
    int i, j;

    for(i = 0; i < n; ++i)
    {
        for(j = 0; j < n; ++j)
        {
            cout << *((arr + i*n) + j);
        }

        cout << endl;
    }
}

int main()
{
    int n, i, j;

    cout << "Enter number of nodes: ";
    cin >> n;

    int arr[n][n] = {{0}}; //Will initialize all elements in the matrix with 0.

    show((int*)arr, n);
}

Upvotes: 0

Views: 93

Answers (2)

A M
A M

Reputation: 15277

The biggest problem here is that you are using C and not C++.

To avoid people gasping and starting religious or political discussion, let's nail it down to:

VLAs (Variable Length Arrays) are not allowed in C++.

Additionally, you should never use raw pointers for owned memory and no pinter arithmetic.

And then the main topic:

Issue in Passing a 2-D array

The used syntax for passing arrays to function is wrong. In C++ arrays can be passed by reference or by pointer. Please see:

void function1(int(&m)[3][4])   // For passing array by reference
{}
void function2(int(*m)[3][4])   // For passing array by pointer
{}

int main()
{
    int matrix[3][4]; // Define 2 dimensional array

    function1(matrix);  // Call by reference
    function2(&matrix); // Call via pointer 
    return 0;
}

Of course we can do all kind of dirty designs with pointers. Even accepting pointer decays. But we should not do it.

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

Variable length arrays is not a standard C++ feature.

Nevertheless you passed to the function a pointer to the first element of a two-dimensional array.

Each "row" of the two-dimensional array has n elements. So if you have a pointer to the first element of the first row then to get the pointer to the first element of the second row you have to write

arr + n

If you want to get the first pointer to the i-th row of the two-dimensional array you have to write

arr + i * n

To get pointer to an element within the row you have to write

( arr  + i * n ) + j

that is the same as

arr + i ( n + j

to get the element pointed to by the pointer you have to dereference the pointer

*( arr + i * n + j )

Upvotes: 0

Related Questions