How to print the address value of a pointer in a C program?

后端 未结 5 1524
走了就别回头了
走了就别回头了 2021-01-03 12:42

I\'m trying to learn how to use the pointer in a C program; my example is as follows:

   #include 
   #include 
   
   int mai         


        
5条回答
  •  盖世英雄少女心
    2021-01-03 13:06

    For printing an "address" (actually a pointer) "%p" is the most common method (note the necessary cast to void*). If you need the address in decimal instead of hexadecimal, you can convert the pointer into an integral value; this is well defined in C (cf. this online C standard draft):

    6.3.2.3 Pointers

    (6) Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

    So the code could look as follows:

    int main(int argc, char *argv[]) {
        int a =10;
        int *p = &a;
        p  = &a;
    
        unsigned long long addrAsInt = (unsigned long long)p;
    
        printf("the adress of a is %llu \n",addrAsInt);
        printf("the adress of a using the pointer is %p \n",(void*)p);
    }
    

提交回复
热议问题