In C/C++, passing an array to a function is different from passing a normal variable, Let’s understand this.
When you pass a normal variable to a function, a copy of the variable is created and passed to the function. Any changes made to the variable inside the function are only reflected in the copy, and not in the original variable outside the function.
However, when you pass an array to a function as an argument, what actually passed is the address of the first element of array. This is an exception to the call by value parameter passing convention. In this case the function can modify the contents of the array and those modifications will be reflected in the original array that was passed to the function.
Here’s an example to illustrate the difference:
#include <stdio.h>
void changeVar(int *x) {
x += 1;
}
void changeArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] += 1;
}
}
int main() {
int x = 5;
changeVar(&x);
printf("%d\n", x); // This will output 6
int arr[] = {1, 2, 3};
int size = sizeof(arr) / sizeof(arr[0]);
changeArray(arr, size);
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]); // This will output 2 3 4
}
printf("\n");
return 0;
}
Output:
6
2 3 4
Explanation:
Function 1: changeVar
void changeVar(int *x) {
x += 1;
}
- Parameter:
int *x
is a pointer to an integer. When you pass a variable’s address to this function, it tries to modify the pointer itself, not the value the pointer is pointing to.
- What it does:
x += 1;
increments the pointer itself, meaning it moves the pointer to point to the next memory location, not the value stored at that location. Therefore, this will not change the actual value ofx
in themain
function.
Note: If you wanted to modify the value that x
points to, you would need to dereference the pointer: *x += 1;
.
Function 2: changeArray
void changeArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] += 1;
}
}
- Parameters:
int arr[]
: This is an array of integers (passed as a pointer).int size
: The size of the array.
- What it does: This function loops through the array, adding 1 to each element. Since arrays in C are passed by reference (actually, a pointer to the first element is passed), modifying
arr[i]
inside the function changes the actual elements in the array.
Main Function:
int main() {
int x = 5;
changeVar(&x); // Pass the address of x
printf("%d\n", x); // Expected output is 6
- What happens:
x
is a simple integer variable initialized to5
. - When calling
changeVar(x)
, the valuex
is passed (instead of its address), which results in a compilation error sincechangeVar
expects a pointer (int *x
) but receives an integer. - Fix: It should be called as
changeVar(&x);
to pass the address ofx
.