Search code examples
cpointerspointer-arithmetic

Pointer Subtraction in C with an array


If I have the following lines of code, why is b-a = 2?

int a[] = {1,2,3,4,5}; 
int *b = &(a[2]); 

Solution

  • To elaborate slightly on Eugene's answer, a is a pointer to the beginning of the array, and a[2] is the same as *(a+2).

    So you could say that the & "cancels" the * as you dereference the pointer and then look at the address of the element that it points to. So *b = &(a[2]) = &(*(a+2)) = a+2. Therefore b-a=2