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
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
#include <stdio.h>
#include <stdlib.h>
void pointerFuncA(int* iptr){
/*Print the value pointed to by iptr*/
printf("Value: %p\n", (void*) iptr );
/*Print the address pointed to by iptr*/
/*Print the address of iptr itself*/
}
int main(){
int iptr = 0;
pointerFuncA( &iptr);
return 0;
}
I think you are looking at something like this, there is no need to re-define the function again in the main....
int* iptr is already a pointer, so you don't need the & in front of it when you write
printf("Address of iptr variable: %x\n", &iptr );
This is how to print a pointer value.
printf("Address of iptr variable: %p\n", (void*)iptr);
Also you have the function prototype for pointerFuncA() in the wrong place, being inside main(). It should be outside of any function, before it is called.
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 )