AlessandroF
AlessandroF

Reputation: 562

Pointer of pointer arithmetic?

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

Upvotes: 1

Views: 225

Answers (1)

Dragoslav Marinica
Dragoslav Marinica

Reputation: 51

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.

Upvotes: 1

Related Questions