问题
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?
回答1:
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).
回答2:
It is correct. The memory position is acquired and dereferenced so first 4 bytes is the integer. You can do *(ar+1) to get the second memory position, dereference that and get the first 4 bytes again. 4 bytes because it is an int if your machine is 32 bits and sizeof(int) == 4
回答3:
I believe that this is proper behavior. Pointers to an array always start at the head of the array--that is the first element. In this case that would be 'ar[0]', and the output should be '1'.
来源:https://stackoverflow.com/questions/17533128/c-dereferencing-arrays