tags:

views:

137

answers:

4

Having code:

int** a = new int*[2];
a[0] = new int(1);
a[1] = new int(2);
cout << "a[0] " << a[0] << '\n';
cout << "a[1] " << a[1] << '\n';
cout << "a[2] " << a[2] << '\n';
cout << "a[0] + 1 " << a[0] + 1 << '\n';//WHY THIS ISN'T == a[1] ?
cout << "*(a + 1): " << *(a + 1) << '\n'; //WHY THIS IS == a[1] ?
cout << "a[0] - a[1] " << static_cast<int>(a[0] - a[1])<< '\n';//WHY THIS IS == 16 not 4?

cout << sizeof(int**);

Questions are included right next to relevant lines in code.

+4  A: 

a[0] and a[1] are contiguous, and they are both pointers, but they do not point to contiguous areas of memory.

That's because the memory pointers returned by the new operator are effectively unpredictable.

In other words, there is no guarantee (in fact quite opposite) that the chunks of memory returned by

a[0] = new int(1);
a[1] = new int(2);

are contiguous.

brainjam
+1  A: 

a[0] + 1 access the first element in a and adds 1.

a[1] access the second element in a.

*(a + 1) is a synonym for a[1].

static_cast<int>(a[0] - a[1]) subtracts the second element in a from the first element in a.

Danvil
+6  A: 

a[0] + 1 means that 1 is added to the value stored in a[0]

*(a + 1) means that 1 * sizeof(int) is added to the memory address of a, and then the value at that location is accessed, meaning you get a[1]

Read more about pointers here.

As for your last question, there is no guarantee it will print any specific value, since the two memory addresses do not have to be contiguous. For me it prints -4 for example.

IVlad
*(a + 1) is indeed the same as a[1], but never use that syntax unless you want to be slapped.
Alan
+1  A: 
  1. You take the value at position zero and add 1 to it.
  2. You take the start of the array advance the pointer by one size of an int pointer and take the value the pointer points to which is a[1].
  3. This could be anything. You are subtracting to different adresses and cast it to int.
pmr