arrayscpointersimplicit-conversionpointer-arithmetic

How to interpret *(ptr) and *(ptr+2) in arrays?


I don't understand how pointers works exactly in arrays.

#include <stdio.h>
int main() {

  int x[5] = {1, 2, 3, 4, 5};
  int* ptr;

  // ptr is assigned the address of the third element
  ptr = &x[2]; 

  printf("value ptr = %d \n", *ptr);   // 3
  printf("address ptr = %d \n", ptr);   // 3
  printf("value ptr+2 = %d \n", *(ptr+2)); // 4
  printf("address ptr+2 = %d \n", (ptr+2)); // 4

  return 0;
}

The result:

value ptr = 3
address ptr = -1931225192
value ptr+2 = 5
address ptr+2 = -1931225184

The difference between ptr and ptr + 2 are 8 bytes. So when ptr is equal to -1931225192 then why isn't ptr + 2 equal to -1931225192 + 2 but instead it is -1931225192 - 8?

Can someone explain how this works? Because it is logical to add 2 to the original value which was -1931225192 but instead this +2 changes into -8.


Solution

    1. When you add an integer to a pointer, you are not adding a fixed number of bytes. You are adding a fixed number of elements. This means you are implicitly adding n*sizeof(int) bytes. To avoid this, you can cast your array to a char * if you want to strictly add a number of bytes.

      Think about it this way: Since the ptr[n] accesses a given element and is defined to be equivalent to *(ptr + n), we see that (ptr + n) without the * simply gets the address of ptr[n].

    2. The address converted to an integer is appears to be negative number, so adding a positive value decreases its magnitude. So the +2 changes to a +8 not a -8.