I’m trying to pass an array as a pointer to a function, but when I do that the function only sees the pointer as an array with 1 variable.
Here is my code:
void make3(int* a) {
int n = sizeof(a) / sizeof(a[0]);
for (int i = 0; i < n; i++) {a[i] = 3;}
}
int main()
{
int a[3] = { 0, 1, 2 };
make3(a);
int* b = a;
for (int i = 0; i < sizeof(a)/sizeof(a[0]); i++) {
cout << *(b + i) << endl;
}
}
The function make3 only changes the first value of the array to 3, instead of all of them.
Is this normal?
If not, what am I doing wrong?
>Solution :
When you pass an array to a function, it decays to a pointer.
int n = sizeof(a) / sizeof(a[0]);
Get evaulate to
int n = sizeof(*a) / sizeof(*(a+0));
Which is 1 everytime.
You should pass size as an argument instead. If you can’t, use std::vector
void make3(std::vector<int> &a) {
for (int i = 0; i < a.size(); i++) {a[i] = 3;}
}
int main()
{
std::vector<int> a{ 0, 1, 2 };
make3(a);
std::vector<int> b = a;
for (int i = 0; i < b.size(); i++) {
cout << b[i] << endl;
}
}