I thought the ptr's address and a's address is the same with each other. And also I thought the ptr's address is the same with its int value converted from pointer.

But the result of console denied me.What's the reason? How can i understand the result.

#include <stdio.h>

int main() {
    int a[5] = {1, 2, 3, 4, 5};
    int *ptr = (int *) ((int) a);

    printf("a's address: %p \n", a);
    printf("ptr's address: %p \n", ptr);
    printf("ptr's int value: %x", (int)ptr);

    return 0;
}

the console's result is

a's address: 0x7ffee8d30600 
ptr's address: 0xffffffffe8d30600 
ptr's int value: e8d30600

ps

I have edited the title, and the original ambiguous title is "What is the difference between pointer's address and pointer's int value"

2 Answers

0
sunhang On

I have understand it. The machine is based with 64bit address. Converting the address to int value will loss the upper value of address. So here the a's address is different from ptr's address.

If to use pointer in C++, we can use intptr_t or preferably uintptr_t

1
Community On

Not really what you are trying to achieve here. An int only contains a 32-bit value. Thus, (int)ptr will only return a 32-bit value of ptr's address, which is the lower 4 bytes you get.