cpointers

Print value and address of pointer defined in function?


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 <stdio.h>
#include <stdlib.h>

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

/*Print the address pointed to by iptr*/

/*Print the address of iptr itself*/
}

int main(){

void pointerFuncA(int* iptr); 

return 0;
}

Obviously this code is just a skeleton but I'm wondering how I can get the communication between the function and the main working, and the syntax for printing the address pointed to and of iptr itself? Since the function is void, how can I send all three values to main?

I think the address is something like:

printf("Address of iptr variable: %x\n", &iptr );

I know it's a simple question, but all the examples I found online just got the value, but it was defined in main as something like

int iptr = 0;

Would I need to create some arbitrary value?

Thanks!


Solution

  • Read the comments

    #include <stdio.h>
    #include <stdlib.h>
        
    void pointerFuncA(int* iptr){
      /*Print the value pointed to by iptr*/
      printf("Value:  %d\n", *iptr );
        
      /*Print the address pointed to by iptr*/
      printf("Value:  %p\n", (void*)iptr );
    
      /*Print the address of iptr itself*/
      printf("Value:  %p\n", (void*)&iptr );
    }
        
    int main(){
      int i = 1234; //Create a variable to get the address of
      int* foo = &i; //Get the address of the variable named i and pass it to the integer pointer named foo
      pointerFuncA(foo); //Pass foo to the function. See I removed void here because we are not declaring a function, but calling it.
       
      return 0;
    }
    

    Output:

    Value:  1234
    Value:  0xffe2ac6c
    Value:  0xffe2ac44