1

I understand how the arithmetic of pointers works, but I have doubts about the one of the pointer of pointer: If I have this code:

    int x;
    int* ptr = &x;
    int** ptrptr = &ptr;

On a standard Windows system, if I do:

printf("%d",ptr);
ptr++;
printf("%d",ptr);

ptr will have a "+4" value than before, obviously because integer needs 4 bytes.

Now, if I do:

printf("%d",ptrptr);
ptrptr++;
printf("%d",ptrptr);

ptrptr will have a "+16" value than before, why?
I apologize if this question has already been posted but I couldn't find out, thank you.

Code:

#include<stdio.h>
int main(void){
    int x;
    int* ptr = &x;
    int** ptrptr = &ptr;

    printf("Pointer: %p\nPointer of pointer: %p\n",(void*)ptr,(void*)ptrptr);
    ptr++;
    ptrptr++;
    printf("Pointer: %p\nPointer of pointer: %p\n",(void*)ptr,(void*)ptrptr);
    return 0;
}

Output:

Pointer: 000000000062FE44
Pointer of pointer: 000000000062FE38
Pointer: 000000000062FE48
Pointer of pointer: 000000000062FE40
17
  • 2
    Do not use %d to print pointers, use %p and cast them to void *. Commented Jan 20, 2019 at 21:22
  • 2
    What is sizeof (int *) on your system? Commented Jan 20, 2019 at 21:27
  • 1
    @AlessandroF Could you change the specifier to %p, cast the parameters to void * and update your results? Like this: printf("Pointer: %p\nPointer of pointer: %p\n", (void*)ptr, (void*)ptrptr); Commented Jan 20, 2019 at 21:39
  • 2
    It seems to me that the difference 62FE40 - 62FE38 is now 8 which is the desired result for 64bit platforms. Commented Jan 20, 2019 at 21:43
  • 1
    Using the wrong specifier invokes undefined behavior, so anything could happen. As you correctly said the difference in ptr and ptr+1 is because on your system an int has 4 bytes. The same applies to ptrptr but the difference is 8 since a pointer has 8 bytes on your system. Commented Jan 20, 2019 at 21:51

1 Answer 1

1

The difference between 0x...FE40 and 0x...FE38 is 8, not 16, and 8 is the correct number of bytes of an address on a 64bit machine.

To hold an int (on your system) you need a box of 4 bytes. So to skip to the next item in memory you add 4 to the address of your initial int.

To hold a pointer_to_int (which is an address on your 64bit system) you need a box of 8 bytes.

A hint: the very numbers you are subtracting are 8-byte-long addresses:

0x00.00.00.00.00.62.FE.40 - 0x00.00.00.00.00.62.FE.38 = 0x08. The dots are only a visual aid.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.