Pass an array by value to a function in C/C++

In this post, we will see how to pass an array by value to a function in C/C++.


 

We know that arguments to the function are passed by value in C by default. However, arrays in C cannot be passed by value to a function and we can modify contents of the array from within the callee function. This is because the array itself is not passed to the function, but a copy of the pointer to its memory address is passed instead. So when we pass an array in a function, it would decay into a pointer regardless of whether the parameter is declared as int[] or not.

 
However, there are few tricks which does allow us to pass an array by value in C/C++.

 

1. Using structures in C

The idea is to wrap the array in a composite data type such as structures in C. This works since struct are passed by value to a function and won’t decay to pointers. In C++, we can use class.

This is demonstrated below:

 

Download   Run Code

Output:

1 2 3 4 5

 
This only works when the struct contains an actual array, and not a pointer to an array. This is because in case of pointers, the address of the original array will be referenced and any change to array contents will be visible to both within and outside the function.

 

2. Create a copy

Another solution is to create a copy of the array inside the callee function and use the copy to perform any modifications. Alternatively, we can also pass a copy of the array to the function.

 

Download   Run Code

Output:

1 2 3 4 5

 

3. Use std::array or std::vector

In C++, the standard approach is to use std::array container to encapsulate fixed size arrays. Unlike a C-style array, it doesn’t decay to pointer automatically and hence can be passed to a function by value. We can also use std::vector container in C++.

 

Download   Run Code

Output:

1 2 3 4 5

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
Notify of