patterncppCritical
Passing a 2D array to a C++ function
Viewed 0 times
functionarraypassing
Problem
I have a function which I want to take, as a parameter, a 2D array of variable size.
So far I have this:
And I have declared an array elsewhere in my code:
However, calling
I do not want to copy the array when I pass it in. Any changes made in
So far I have this:
void myFunction(double** myArray){
myArray[x][y] = 5;
// etc...
}
And I have declared an array elsewhere in my code:
double anArray[10][10];
However, calling
myFunction(anArray) gives me an error.I do not want to copy the array when I pass it in. Any changes made in
myFunction should alter the state of anArray. 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, [10][10] and [5][5]. How can I do this?Solution
There are three ways to pass a 2D array to a function:
-
The parameter is a 2D array
-
The parameter is an array containing pointers
-
The parameter is a pointer to a pointer
-
The parameter is a 2D array
int array[10][10];
void passFunc(int a[][10])
{
// ...
}
passFunc(array);-
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);-
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);Code Snippets
int array[10][10];
void passFunc(int a[][10])
{
// ...
}
passFunc(array);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);int **array;
array = new int *[10];
for(int i = 0; i <10; i++)
array[i] = new int[10];
void passFunc(int **a)
{
// ...
}
passFunc(array);Context
Stack Overflow Q#8767166, score: 542
Revisions (0)
No revisions yet.