Print value and address of pointer defined in function?

后端 未结 5 2024
[愿得一人]
[愿得一人] 2021-02-07 23:29

I think this is a really easy thing to code, but I\'m having trouble with the syntax in C, I\'ve just programmed in C++.

#include 
#include 

        
5条回答
  •  南方客
    南方客 (楼主)
    2021-02-07 23:49

    To access the value that a pointer points to, you have to use the indirection operator *.

    To print the pointer itself, just access the pointer variable with no operator.

    And to get the address of the pointer variable, use the & operator.

    void pointerFuncA(int* iptr){
        /*Print the value pointed to by iptr*/
        printf("Value:  %x\n", *iptr );
    
        /*Print the address pointed to by iptr*/
        printf("Address of value: %p\n", (void*)iptr);
    
        /*Print the address of iptr itself*/
        printf("Address of iptr: %p\n", (void*)&iptr);
    }
    

    The %p format operator requires the corresponding argument to be void*, so it's necessary to cast the pointers to this type.

提交回复
热议问题