Eric
Eric

Reputation: 2076

Passing 2D array with variable Size

I'm trying to pass a 2D array from a function to another function. However, the size of the array is not constant. The size is determined by the user.

I've tried to research this, but haven't had much luck. Most code and explanations are for a constant size of the array.

In my function A I declare the variable and then I manipulate it a bit, and then it must be passed to Function B.

void A()
{
      int n;
      cout << "What is the size?: ";
      cin >> n;

      int Arr[n-1][n];

      //Arr gets manipulated here

      B(n, Arr);
}

void B(int n, int Arr[][])
{
    //printing out Arr and other things

}

Upvotes: 4

Views: 9887

Answers (3)

user2249683
user2249683

Reputation:

C++ does not support variable length arrays. Having C99 and compile it C only, you may pass the array like this:

#include <stdio.h>

void B(int rows, int columns, int Arr[rows][columns]) {
    printf("rows: %d, columns: %d\n", rows, columns);
}

void A() {
    int n = 3;
    int Arr[n-1][n];
    B(n-1, n, Arr);
}


int main()
{
    A();
    return 0;
}

Note: Putting extern "C" { } around the functions does not resolve the C++ incompatibility to C99:

  g++ (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2:
  error: use of parameter ‘rows’ outside function body
  error: use of parameter ‘columns’ outside function body
  warning: ISO C++ forbids variable length array

Upvotes: 3

user1804599
user1804599

Reputation:

Use std::vector if you want dynamically-sized arrays:

std::vector<std::vector<int>> Arr(n, std::vector<int>(n - 1));
B(Arr);

void B(std::vector<std::vector<int>> const& Arr) { … }

Upvotes: 11

Pai
Pai

Reputation: 272

Array size needs to be constant. Alternatively, you can use std::vector<std::vector<int>> to denote a dynamic 2D array.

Upvotes: 3

Related Questions