1

Hi all I have a question about the following code and want to verify some of my assertions.

int array[] = {1,2,3,4};
int* ptr = &array[1];

Does &array[1] mean I get the address of the array and add 1 to it, deference that address to see the actual integer and then take the address of the integer which is stored in that address?

How is this done? Is there a operator[](int index) for array that returns a reference and then we takes its address?

I want to understand what the machine is actually doing and the language semantics for this.

djf
  • 6,592
  • 6
  • 44
  • 62
Blair Davidson
  • 901
  • 12
  • 35
  • It could be done like that, but it would make no sense to do so. For a practical, actual implementation, the generated code is the same as that of normal pointer arithmetic using the `+` operator (`array + 1`). –  Jun 12 '13 at 13:38
  • Array-pointer-decay is what you're trying to understand: http://stackoverflow.com/q/4810664/183120 – legends2k Jun 12 '13 at 13:42

4 Answers4

6
int* ptr = &array[1];

is equivalent to :

int* ptr = & ( *(array + 1) );

*(array+1) matches the second cell of your array. Then you're affecting the address of this cell to your pointer. What you're doing is equivalent to :

int* ptr = array+1
ibi0tux
  • 2,481
  • 4
  • 28
  • 49
6

Does this mean get the address of the array and add 1 to it, dereference that address to see the actual integer and then take the address of the integer which is stored in that address?

Yes. Equivalently, it just means "add one to the address of the array", since dereferencing then taking the address gives you the address you started with.

How is this done? Is there a operator[](int index) for array that returns a reference and then we takes its address?

Almost. The built-in subscript operator, when used to apply an index to a pointer as p[i], is defined to give an lvalue referring to *(p+i). When applied to an array, the array is first converted to a pointer to its first element. That is one of the standard implicit conversions: the array-to-pointer conversion, sometimes referred to as "decaying". Taking the address of the lvalue gives a pointer to the array element.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

Yes. You will find that you can set int* arrPtr=array;, meaning that array can be treated as a pointer. array[1]; means "take the pointer to the start of array array, shift it over one, and dereference. &array[1]; means "get the pointer to that dereferenced value." array[1]; is equivalent to *(array+1);.

IanPudney
  • 5,941
  • 1
  • 24
  • 39
0

Probably because of different possible types, the array index is first executed (read: array[1] is first 'get') and then & goes into action and get's the address. While if you had a long long, get the address of array[0] and add 1 to it you would be reading the first 8bytes from another alignment (you are reading the last 3 bytes of the 1st index , then 7 bytes from the second )