2

I have trouble in understanding the difference between the two: (int *) (&a[2]) and *(&a[2]). I understand &a[2] gets the address of a[2] and *gets the value in that address, so *(&a[2]) get the value of a[2], which is 3. But how come (int *)(&a[2]) returns an address? Thank you!

Output:

3
0x7fff40144888

Codes:

include<iostream>
using namespace std;
int main()
{
        int a[3]={1,2,3};
        //cout << *(a+2) << endl;
        cout << *(&a[2]) << endl;
        cout << (int*)(&a[2]) << endl;
}
daydayup
  • 2,049
  • 5
  • 22
  • 47

4 Answers4

4

*(&a[2]) gets the value a[2] (a simple reference then dereference)

(int*)(&a[2]) gets the address of a[2] and casts it to an int* (no dereference)

The (int*) does not deference the pointer, it casts it to an int* (which is redundant since it already is an int*)

Note: int* is a type, just as int is a type.

brettwhiteman
  • 4,210
  • 2
  • 29
  • 38
4

The ( int*) is doing c style casting.

All the following 3 statements are going to print same result and they are equivalent in your example's context:

    cout << (int*)(&a[2]) << endl;
    cout << &a[2] << endl;
    cout <<static_cast<int*>( &a[2]) << endl;

Demo: http://coliru.stacked-crooked.com/a/c95796c19750400b

Steephen
  • 14,645
  • 7
  • 40
  • 47
3

* will dereference a pointer

(int*) is a C-style cast to int*.


Since (&a[2]) produces a pointer to the number 3...

* (&a[2]) will dereference the pointer.

(int*) (&a[2]) will cast the pointer to an int pointer. (Which it already is - so it has no effect)

Community
  • 1
  • 1
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
1

The first one (*(&a[2])) says get the element at index 2 of a, get a pointer to that element (aka the address in memory) (&), and then get the value at that address (*), so essentially the & and * operators cancel out and you get a[2] which is 3.

The second one ((int*)(&a[2])) says get the element at index 2 of a, get a pointer to that element (&), and then cast that pointer to be an int pointer ((int *)) (i.e. interpret the value at that address as an integer). So the entire expression will give you the address in memory of a[2], which happens to be 0x7fff40144888.

puzzlepalace
  • 660
  • 5
  • 13
  • 2
    "which happens to be 0x7fff40144888" - lol as if it's going to be the same for everyone – brettwhiteman Jul 16 '15 at 00:48
  • 1
    I mean that in this particular instance of executing the program it happens to be 0x7fff40144888, of course it's not the same for everyone / across executions... – puzzlepalace Jul 16 '15 at 00:50