How to get address of a pointer in c/c++?

前端 未结 10 1873
逝去的感伤
逝去的感伤 2020-12-07 14:43

How to get address of a pointer in c/c++?

Eg: I have below code.

int a =10;
int *p = &a;

So how do I get addre

10条回答
  •  囚心锁ツ
    2020-12-07 15:45

    First, you should understand the pointer is not complex. A pointer is showing the address of the variable.

    Example:

    int a = 10;
    int *p = &a;  // This means giving a pointer of variable "a" to int pointer variable "p"
    

    And, you should understand "Pointer is an address" and "address is numerical value". So, you can get the address of variable as Integer.

    int a = 10;
    unsigned long address = (unsigned long)&a;
    
    // comparison
    printf("%p\n", &a);
    printf("%ld\n", address);
    

    output is below

    0x7fff1216619c
    7fff1216619c
    

    Note:

    If you use a 64-bit computer, you can't get pointer by the way below.

    int a = 10;
    unsigned int address = (unsigned int)&a;
    

    Because pointer is 8 bytes (64 bit) on a 64-bit machine, but int is 4 bytes. So, you can't give an 8-byte memory address to 4 bytes variable.

    You have to use long long or long to get an address of the variable.

    • long long is always 8 bytes.
    • long is 4 bytes when code was compiled for a 32-bit machine.
    • long is 8 bytes when code was compiled for a 64-bit machine.

    Therefore, you should use long to receive a pointer.

提交回复
热议问题