In C, how does arithmetic between a pointer and an array work?

c, pointers

Solution

`I think y should be 4*sizeof(int)`

Good thinking, and guess what? It is giving `4*sizeof(int)`, but you're not looking at it right. ;)

When you're playing with pointers, you're looking at addresses, so let's check out some addresses

int x[] = { 1, 4, 8, 5, 1, 4 };

//Just for fun, what is the address of each element in the array?
printf("%#x, %#x, %#x, %#x, %#x, %#x\n", x+0, x+1, x+2, x+3, x+4, x+5);

ptr = x + 4;

printf("%#x - %#x\n", ptr, x);  // Give us the address of ptr in hex
                                // and give us the address of x
y = ptr - x;                    

printf("%d\n", y);

Output:

   x[0]         x[1]        x[2]        x[3]         x[4]       x[5]
0xbf871d20, 0xbf871d24, 0xbf871d28, 0xbf871d2c, 0xbf871d30, 0xbf871d34

   ptr           x
0xbf871d30 - 0xbf871d20

4

So ptr is `x+4` (which is really `x + 4*sizeof(int)` or `x+16` in your case). And we're going to subtract from that `x` or the base address, so the actual math is `0x30 - 0x20 = 0x10` or in dec `16`.

The reason you're seeing `4` on the output is because the compiler knows you're doing operations on `int *` so it's dividing that `16` by `sizeof(int)` for you. Nice hm?

If you want to see the actual value you need to do something like this:

int one, two;
...
one = (int)ptr;  //get the addresses, ignore the "type" of the pointer 
two = (int)x;
y = one - two;

Now `y` will give you 0x10(hex) or 16(dec)

Problem

What should be the value of y and why? ``` int x[] = { 1, 4, 8, 5, 1, 4 }; int *ptr, y; ptr = x + 4; y = ptr - x; ``` I think y should be 4*sizeof(int), but it is giving 4. Why ?

Original source