Arrays are often passed to functions as parameters in C++. However, since arrays decay into pointers when passed to a function, there are some subtle issues and limitations to keep in mind.
Understanding Array Parameters in Functions
- When an array is passed to a function, it decays into a pointer to its first element.
- The function receives only the address, not the whole array.
- Using sizeof inside the function returns the pointer size, not the array size.
- Therefore, the array length cannot be determined correctly inside the function.
#include <iostream>
using namespace std;
void f(int a[]) {
int n = sizeof(a) / sizeof(int); // Incorrect size calculation
for (int i = 0; i < n; i++) {
cout << a[i] << ' ';
}
cout << '\n';
}
void f(int a[], int N) {
int n = N; // Correct size passed explicitly
for (int i = 0; i < n; i++) {
cout << a[i] << ' ';
}
cout << '\n';
}
int main() {
int a[] = {1, 2, 3, 4, 5};
int n = sizeof(a) / sizeof(int); // Correct size calculation in main
for (int i = 0; i < n; i++) {
cout << a[i] << ' ';
}
cout << '\n';
f(a);
f(a, n);
return 0;
}
Output
1 2 3 4 5 1 2 1 2 3 4 5
Explanation:
- In the "main" function, the array a has 5 elements.
- The size is correctly calculated in main using sizeof(a) / sizeof(int) because a is treated as an array there.
- When the array is passed to "f(int a[])", it decays into a pointer.
- sizeof(a) inside this function gives the size of the pointer, not the array, so the size calculation becomes incorrect.
- In "f(int a[], int N)", the array size is passed explicitly as N.
- This is the correct way to handle arrays when their size is needed inside a function.