Thread: how can i pass 2d and 3d array by reference?

1. how can i pass 2d and 3d array by reference?

in the main function, i created 2 arrays, one is 2d array and another one is 3d, i want to pass thoes array to the function for some calculation. how can i write the function declaration??
Code:
```int main(void)
{
char a[n][n][n];
int b[n][n];

someFunction(a, b);
}

someFunction( char* a[][], int* b[]){
//do some operation here
}```
i dont know how to write the declaration of the function
i need to pass the whole 3d and 2d array to that function
how can i do it?
thanks for help!

2. Copy/paste.

someFunction( char a[n][n][n], int b[n][n] )

3. sorry, I want to pass the whole array into the function, not one element in the array.
how abt the declaration in the function?

4. Perhaps you should just try the code.

That does pass the whole array, as a pointer.

You could write it like this if you want, if you desperately need to see some *'s in the declaration, but it doesn't change a thing.
someFunction( char (*a)[n][n], int (*b)[n] )

5. Or you could use C++ std::array `s and do it in a less cluttered way.
The declaration looks like (for a 2d(3x3) integer one):
array<array<int,3>,3> my_array;

The function prototype would be something like:
void foo(array<array<int,3>,3>& my_array);

After that you can forget that they are std::arrays and just treat them as normal ones(except possibly some pointer notations...where you should use iterators)

6. someFunction( char (*a)[n][n], int (*b)[n] )
that is in the call function, right?
but how to write the declaration
someFunction( char *a, int *b)?
sorry for my foolish question, i have not write the c program for long long time lol

7. You were calling it just fine in post #1, all you needed to do was get the parameter type correct (post 2) and you were done.

You've over-thinking the problem!

8. Originally Posted by johnny8888
sorry for my foolish question, i have not write the c program for long long time lol
[/FONT]
Are you writing C? ...Or C++?

9. IMO it's not a bad idea to write:
Code:
```void someFunction( char (&a)[n][n][n], int (&b)[n][n]){
//do some operation here

}```
That's literally an array reference. The reason is, unlike pointer syntax, for which the first dimension is not checked, with this syntax it is. So you cannot pass an array that's not NxNxN. Otherwise the use is the same, except sizeof(a) and sizeof(b) will return the size of the array. Especially with multidimensional arrays, it is often the case that if the user is passing an array that doesn't have the same dimension, then they are doing something wrong.

10. Originally Posted by johnny8888
i created 2 arrays, one is 2d array and another one is 3d, i want to pass thoes array to the function for some calculation.
Those arrays probably mean something that you can name. Especially in the case of the 3D array, I would rather write a class to contain it, then pass objects of that class around (by (const) reference).