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
%dto print pointers, use%pand cast them tovoid *.sizeof (int *)on your system?%p, cast the parameters tovoid *and update your results? Like this:printf("Pointer: %p\nPointer of pointer: %p\n", (void*)ptr, (void*)ptrptr);62FE40-62FE38is now8which is the desired result for 64bit platforms.ptrandptr+1is because on your system aninthas 4 bytes. The same applies toptrptrbut the difference is8since a pointer has 8 bytes on your system.