Print value and address of pointer defined in function?
Address are some memory values which are written in hexadecimal notation starting with 0x
/Value pointed to by the pointer iptr/
printf("Value is: %i", *iptr);
Address pointed to by the pointer will be the value of the iptr pointer itself
/print the address pointed to by the iptr/
printf("Address is: %p", iprt);
/print the address of iptr itself/
printf("Address of iptr: %p", &iptr )
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.
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", iptr );
/*Print the address of iptr itself*/
printf("Value: %p\n", &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