How to pass an array by value in C ?
In C programming, arrays are always passed as pointers to the function. There are no direct ways to pass the array by value. However, there is trick that allows you to simulate the passing of array by value by enclosing it inside a structure and then passing that structure by value. This will also pass the member array by value.
Let's take a look at an example:
#include <stdio.h>
typedef struct {
int arr[5];
} S;
void f(S s) {
// Modifying the first element
s.arr[0] = 100;
printf("Inside function: arr[0] = %d\n", s.arr[0]);
}
int main() {
// Structure that encloses the array
S s = {{1, 2, 3, 4, 5}};
// Pass the structure s by value
f(s);
printf("Inside main: arr[0] = %d", s.arr[0]);
return 0;
}
typedef struct {
int arr[5];
} S;
void f(S s) {
// Modifying the first element
s.arr[0] = 100;
printf("Inside function: arr[0] = %d\n", s.arr[0]);
}
int main() {
// Structure that encloses the array
S s = {{1, 2, 3, 4, 5}};
// Pass the structure s by value
f(s);
printf("Inside main: arr[0] = %d", s.arr[0]);
return 0;
}
Output
Inside function: arr[0] = 100 Inside main: arr[0] = 1
Explanation: In this example, the array is stored inside a structure S, which is passed to the f() function by value. As the structure is passed by value, the function modifies the copy of the array inside the structure, but the original array is left unchanged in the main() function, demonstrating how the array is passed by value.
By Copying the Array
The other method to simulate this pass by value behaviour for array is to first create a copy of the array and pass it to the function or just pass the original array and create a copy in the passed function.
#include <stdio.h>
#include <string.h>
// Function that takes array
void f(int *arr, int n) {
// Create a copy
int cpy[n];
memcpy(cpy, arr, n * sizeof(int));
// Modify the array elements
cpy[0] = 100;
printf("Inside function: %d\n", cpy[0]);
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
f(arr, 5);
printf("Inside main: %d", arr[0]);
return 0;
}
// Function that takes array
void f(int *arr, int n) {
// Create a copy
int cpy[n];
memcpy(cpy, arr, n * sizeof(int));
// Modify the array elements
cpy[0] = 100;
printf("Inside function: %d\n", cpy[0]);
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
f(arr, 5);
printf("Inside main: %d", arr[0]);
return 0;
}
Output
Inside function: 100 Inside main: 1
Explanation: In this code, we create a copy of the original array using memcpy() and pass the copy to the f() function. The function modifies the copied array, leaving the original array unchanged, effectively simulating passing the array by value.