Search code examples
carrayspointer-arithmeticaddressof

Finding the difference between the addresses of elements in an array


I have an exam revision question on pointer arithmetic and one part where we are subtracting the address of two array variables is not making sense to me.

Well one array actually equals the other. I understand the individual outputs for each array variable and in this case the difference between the two addresses is 16, given an int = 4 bytes on this os.

What I don't understand is why the subtraction gives 4. My logic would be that they are 4 positions apart in the array, but this doesn't make sense to me.

int main(void)
{

int oddNums[5] = {1, 3, 5, 7, 9};
int *ip = oddNums;

printf("&oddNums[4] %d - ip %d= %d\n",&oddNums[4], ip,  &oddNums[4] - ip);
/*prints &oddNums[4] 2686740 - ip 2686724= 4*/

   return EXIT_SUCCESS;
}

Solution

  • Subtraction returns 4 because it returns its result in terms of sizeof(<array-element>). This is done to make subtraction an inverse of addition, which also operates in terms of array element size.

    Recall that if a is an array and i is an integer, then a+i is the same as &a[i], so the addition must consider the size of the element. In order to follow the rules of the math, the subtraction must divide out the size of an element as well.

    This makes pointer arithmetics a lot easier, because the operations of addition and subtraction take care of dealing with the size of array element. Without this rule, one would need to keep dividing or multiplying results of addition or subtraction by the size of an element in order to get the address of the desired element or to get the offset. This is error-prone, and it is also hard to read. Finally, this would create maintenance nightmare in situations when you change element size from one byte to several bytes, and whoever coded the algorithm has forgotten to multiply or divide by sizeof.