Passing a 2D array to a C function

0 votes

I have a method that will take a 2D array of configurable size as a parameter.

So far, I've got:

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

And I have declared an array elsewhere in my code:

double anArray[10][10];

However, when I call myFunction(anArray), I get an error. I don't want to make a copy of the array when I send it in. 

Any modifications to myFunction should have an effect on the state of anArray. 

If I understand well, I simply want to send a pointer to a 2D array as a parameter. 

The function must also take arrays of varying sizes. For instance, [10][10] and [5][5]. How can I accomplish this?

Aug 2, 2022 in C++ by Nicholas
• 7,760 points
33,120 views

1 answer to this question.

0 votes

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])
    {
        // ...
    }
    passFunc(array);
    
  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
    {
        // ...
    }
    passFunc(array);
    
  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)
    {
        // ...
    }
    passFunc(array);
answered Aug 2, 2022 by Damon
• 4,960 points
0 votes
How to pass 2D array to a function in c language
answered Oct 13, 2023 by Artp

edited Mar 5

Related Questions In C++

0 votes
0 answers

What is the C++ function to raise a number to a power?

What's the best way to raise a n ...READ MORE

Jun 1, 2022 in C++ by Nicholas
• 7,760 points
852 views
0 votes
0 answers

How to implement 2D vector array?

I'm using the vector class in the ...READ MORE

Jun 1, 2022 in C++ by Nicholas
• 7,760 points
950 views
0 votes
0 answers

How to implement 2D vector array?

I'm using the vector class in the ...READ MORE

Jun 1, 2022 in C++ by Nicholas
• 7,760 points
668 views