RogerDarwin RogerDarwin - 10 months ago 47
C++ Question

Passing a 2D array to a C++ function

I have a function which I want to take, as a parameter, a 2D array of variable size.

So far I have this:

void myFunction(double** myArray){
myArray[x][y] = 5;

And I have declared an array elsewhere in my code:

double anArray[10][10];

However, calling
gives me an error.

I do not want to copy the array when I pass it in. Any changes made in
should alter the state of
. If I understand correctly, I only want to pass in as an argument a pointer to a 2D array. The function needs to accept arrays of different sizes also. So for example,
. How can I do this?


There are three ways to pass a 2D array to a function:

  1. The parameter is a 2D array

    int array[10][10];
    void passFunc(int a[][10])
        // ...
  2. The parameter is an array containing pointers

    int *array[10];
    for(int i = 0; i < 10; i++)
        array[i] = new int[10];
    void passFunc(int *a[10]) //Array containing pointers
        // ...
  3. The parameter is a pointer to a pointer

    int **array;
    array = new int *[10];
    for(int i = 0; i <10; i++)
        array[i] = new int[10];
    void passFunc(int **a)
        // ...