Search code examples
cpointerspointer-arithmetic

How do variable types affect pointer arithmetic work in C?


I'm having trouble understanding pointer's arithmetic.

Let int B=0, *p=&B, **V=&p and sizeof(int)=4, sizeof(*int)=8

What does the instruction (*V)[1] do? To me, what I see is that (*V)[1] is equivalent*(*V+1), so what should happen is, we dereference V (which is a pointer to a pointer to an int) and sum 1 to the content of that variable, which is an address. That variable is a pointer and we're assuming sizeof(*int)=8, so in theory we should sum 1 * sizeof(*int) (which is 8) to whatever address is stored in the pointer p to which the pointer V points.

The solution, however, says to sum 4 (1 + sizeof(int)). Is it wrong or is my thinking wrong?


Solution

  • The solution you reference is correct.

    The expression *V has type int *, so it points to an array of 1 or more int. So because it points to an int, when pointer arithmetic happens the size of the datatype it point to (sizeof(int), i.e. 4) is multiplied by the given value (1). So if you were to print the values of *V and *V + 1 you would see that they differ by 4.

    There is however a problem with (*V)[1], equivalently *(*V + 1). Since *V points to B, *V + 1 points one element past B. This is legal since a pointer can point to one element past the end of an array (or equivalently a single object which is treated as an array of size 1). What is not legal however is to dereference that pointer. Doing so invokes undefined behavior.