 # Passing an array as a procedure argument

I would like to know how can I pass a 2D array as a function argument in C++… I would like to be able to do something on the array and returning it on main()…

For example:

Pass an array to a function and find the minimum value of a given row… after declaring the array on main()… Is that possible? I tried with pointers but got confused along the way… any help would be greatly appreciated

1 Like

I have always similar problem with C/C++…

Let’s do that step by step.

## Array

Let’s try something easier - 1D array. I believe you can declare and use arrays.

``````#define LEN 4
...
int main() {
int a[LEN];
...
}
``````

so if you want, you can pass that array to a function

``````void foo( int a[LEN] ) {
...
}
``````

but you have to realize that array is copied to the function, so any change in the function won’t be visible in `main()`, you can try…

Tried? Maybe you tried (maybe not), maybe you simply know that copying is the problem. While you know the LEN you can pass just address of the first argument to function.

Declare correct function for array modification as

``````void mod( int* a ) {
...
}
``````

and call this function as

``````mod( &a );
``````

I hope so far so good, let’s allocate the memory dynamically.

``````int n = 4;
int* b = (int*)malloc( n * sizeof(int) );
``````

then correct modification function is

``````void mod2( int** b, int n ) {
...
}
``````

very important thing is how to access value in function

``````// see the (*b), (*b)[i] it's not the same as *b[i]
for (int i = 0; i < n; ++i ) (*b)[i] = 2* (*b)[i]; // multiplies by 2
``````

and you call it this way

``````mod2( &b, n );
``````

## Matrix

Finally 2D array (aka matrix). It’s not complicated a lot comparing to dynamically allocated 1D array. You just have to allocate 2 dimensions

``````int R = 2;
int C = 3;
int** matrix = (int**)malloc( R * sizeof(int*) );
for ( int i = 0; i < R; ++i ) {
matrix[i] = (int*)malloc( C * sizeof(int) );
}
``````

and modify it in a similar way

``````modify( &matrix, R, C );
``````

while `modify` function is

``````void modify( int*** mat, int R, int C ) {
...
}``````
4 Likes

Thank you very much, this helped me greatly!! This can be closed now