1

I am just learning C++ and a little confused about arrays and references. I wrote the following program:

void printArray(int arr[]) {
    cout << arr[0] << arr[1] << arr[2] << endl;
}

int main() {
    int arr[3] = {5, 7, 9};
    int *aPtr = &arr[0];
    cout << aPtr[0] << aPtr[1] << aPtr[2] << endl;
    int *bPtr = arr;
    cout << bPtr[0] << bPtr[1] << bPtr[2] << endl;
    printArray(arr);
}

The output is :

579
579
579

And I have two questions:

  1. Is array in C++ a reference? I mean, can I state that i = &i[0]?
  2. If answer to the first question is yes, can I say that as array is reference we don't need to use & in arguments of the function printArray. I mean, we don't declare the function this way printArray(int &arr[])?
Pavel_K
  • 8,216
  • 6
  • 44
  • 127
  • 1
    Possible duplicate of [What is array decaying?](https://stackoverflow.com/questions/1461432/what-is-array-decaying) – UnholySheep May 13 '18 at 16:55
  • 1
    You actually don't have a single reference in that code. You only have pointers and the addressof-operator – UnholySheep May 13 '18 at 16:56
  • It's of course good to know about C-style arrays and how/when they decay to pointers, but in the long run I'd advise to *not* use them in your own code. Instead use [std::array](http://en.cppreference.com/w/cpp/container/array) when the size is fixed at compile time or [std::vector](http://en.cppreference.com/w/cpp/container/vector) when you need a dynamically sized array. – Jesper Juhl May 13 '18 at 17:00
  • `&i[0]` is a pointer. Pointers and references are different things. References are aliases; new names for an already existing object. – axiac May 13 '18 at 17:00
  • @axiac: Actually a reference binds to a memory location, just like a pointer does. There certainly are syntactic differences, but the only semantic difference between a reference and a const pointer is the lifetime extension that occurs when a temporary object (prvalue) is directly bound to a reference. – Ben Voigt May 13 '18 at 17:25

1 Answers1

6

No, an array is not a reference in C++. It is an array, the length of which forms part of the type (so for example the type of int[3] is not the same as that of int[42]).

What can be confusing is that C++ inherits from C the strange features that

  1. array function parameters have their type "adjusted" to pointer
  2. array names can "decay" to pointers very easily. That makes it possible to assign an array to a pointer.

Point 1 above means that these two function declarations are completely equivalent:

// two ways do declaring the same function
void foo(int a[42]);
void foo(int* a);

and point 2 means you can call the function passing it an array:

int a[3] = {};
int b[100] = {};

foo(a);
foo(b);

and other funny stuff, for example, the type of expression +a being int*.

juanchopanza
  • 210,243
  • 27
  • 363
  • 452