Search code examples
c++arraysdereference

C++ Dereferencing Arrays


I never read anything about dereferencing arrays like pointers and I believe it shouldn't work. But the following code does work using QT Creator and g++ 4.8:

int ar[9]{1,2,3,4,5,6,7,8,9};
cout << *ar << endl; //prints the first element of ar

Is it proper behavior or just the compiler fixing the code?


Solution

  • You cannot dereference an array, only a pointer.

    What's happening here is that an expression of array type, in most contexts, is implicitly converted to ("decays" to) a pointer to the first element of the array object. So ar "decays" to &ar[0]; dereferencing that gives you the value of ar[0], which is an int.

    This recent answer of mine discusses this in some detail for C. The rules for C++ are similar, but C++ has a few more cases where the conversion does not occur (none of which happen in your code).