Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending variable size 2D array to function in C++

I am trying to write a function which takes variable size array and prints it. But i am having problem in function declaration argument list while compiling.

The error is:

cannot convert ‘int (*)[(((sizetype)(((ssizetype)r) + -1)) + 1)]’ to ‘int**’ for argument ‘1’ to ‘void printHalf(int**, int, int)’
  printHalf( b, r, r);

Code:

#include <iostream>

using namespace std;

void printHalf( int **a, int row, int col ) {  // Problem is here.
    for( int i=0; i < row; i++) {
        for( int j=0; j < col; j++) {
            if( i <= j) {
                cout << a[i][j] << " ";
            }
        }
        cout << endl;
    }
}

int main() {
    int r;
    cout << "No. of rows: ";
    cin >> r;
    int b[r][r];

    for( int i=0; i < r; i++) {
        for( int j=0; j < r; j++) {
            cin >> b[i][j];
        }
    }

    printHalf( b, r, r);
    return 0;
}

What is causing this error, and how do i pass various arrays to function?

like image 571
Max Payne Avatar asked Nov 22 '25 06:11

Max Payne


2 Answers

A 2D array of [N][M] is laid out the same in memory as a 1D array of [N*M].

void printHalf( int *a, int row, int col ) {  // Problem is here.
    for( int i=0; i < row; i++) {
        for( int j=0; j < col; j++) {
            if( i <= j) {
                cout << a[i*col+j] << " ";
            }
        }
        cout << endl;
    }
}

Then you can call it with printHalf( &b[0][0], r, r).

Your fundamental misunderstanding is the relationship between arrays and pointers. Arrays aren't pointers. An int** can be viewed as an array of int*, which isn't what you have. b[0] gets you an int[r]. This is different to an int*. b[0][0] gets you the first int.

like image 99
Simple Avatar answered Nov 23 '25 19:11

Simple


Problems that I see

  1. C++ does not allow declaration of variable length arrays. Hence,

    int b[r][r];
    

    is wrong.

  2. A one dimensional array decays to a pointer but a two dimensional array does not decay to a pointer to pointer. Even if you had b defined correctly, such as:

    int b[10][10];
    

    you cannot use b as an argument to a function that expects an int**.

Solution

I suggest use of std::vector.

std::vector<std::vector<int>> b(r, std::vector<int>(r));

Change the function printHalf accordingly.

void printHalf( std::vector<std::vector<int>> const& b ) { ... }

You don't need row and col as arguments since that information can be obtained from the std::vector.

like image 20
R Sahu Avatar answered Nov 23 '25 19:11

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!