Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why, when I use a pointer to pass an array to a function, the array's length appears to be 1?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading