0

I'm trying to learn how to use pointers and references using a video course and I find pointers and references to be quite complex.

I'm trying to make a really basic exercise so I can get how it works. It looks like this:

void print(int &array, int size)
{
    for (int i = 0; i < size; i++)
    {
        cout << array[i] << " ";
    }
}

int main()
{
    int n, a[10];
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    print(a, 5);
    return 0;
}

It is not working because I'm passing an array as a reference. If I change the function prototype to this

void print(int *array, int size)

it works perfectly.

Can anyone explain me why? I think in this situation using a pointer or a reference should be the same. Both would lead to the array. Am I wrong?

TylerH
  • 20,799
  • 66
  • 75
  • 101

2 Answers2

2

The type int &array declares array as a reference to a single int variable, not to an array of int elements.

The reason it works with pointers is because arrays naturally decays to pointers to their first element. I.e. when you pass a what you're really passing is &a[0], which is of type int*.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

Passing by value means copying the parameter given to a variable with the name of the parameter. This variable can then be accesed in the function. So when you do something like:

void MyFunction(int* myptr);

What is really passed is a copy of the pointer. That is, it copies the value of the pointer given as the parameter (the address it holds) to myptr. The copy pointer then accesses the value at that address which is the same as the one that the original pointer points to. So when you do this:

void print(int* array, int size);

What is really passed is a copy of the address to the first element. When you declare an array like this:

int array[20];

That array is really a pointer so if you refer to it as:

 *array

Then it would be the same as:

array[0]

Passing by reference means that the value passed refers to the same place in memory as the original.

int print(int& array, int size)

This function just takes an int value (not an array), and the function is free to modify the value, as those changes will affect the original variable in the caller function.

I hope that clarifies the difference.

DarkAtom
  • 2,589
  • 1
  • 11
  • 27