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

前端 未结 10 1877
逝去的感伤
逝去的感伤 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:39

    you can use this

    in C

    int a =10;
    int *p = &a;     
    int **pp = &p;
    printf("%u",&p);
    

    in C++

    cout<<p;
    
    0 讨论(0)
  • 2020-12-07 15:39

    In C++ you can do:

    // Declaration and assign variable a
    int a = 7;
    // Declaration pointer b
    int* b;
    // Assign address of variable a to pointer b
    b = &a;
    
    // Declaration pointer c
    int** c;
    // Assign address of pointer b to pointer c
    c = &b;
    
    std::cout << "a: " << a << "\n";       // Print value of variable a
    std::cout << "&a: " << &a << "\n";     // Print address of variable a
    
    std::cout << "" << "" << "\n";
    
    std::cout << "b: " << b << "\n";       // Print address of variable a
    std::cout << "*b: " << *b << "\n";     // Print value of variable a
    std::cout << "&b: " << &b << "\n";     // Print address of pointer b
    
    std::cout << "" << "" << "\n";
    
    std::cout << "c: " << c << "\n";       // Print address of pointer b
    std::cout << "**c: " << **c << "\n";   // Print value of variable a
    std::cout << "*c: " << *c << "\n";     // Print address of variable a
    std::cout << "&c: " << &c << "\n";     // Print address of pointer c
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 15:47

    You can use %p in C

    In C:

    printf("%p",p)
    

    In C++:

    cout<<"Address of pointer p is: "<<p
    
    0 讨论(0)
提交回复
热议问题