Here is a basic C program about pointers:
#include <stdio.h>
int main() {
int variable = 20;
int *pointerToVariable;
pointerToVariable = &variable;
printf("Address of variable: %x\n", &variable);
printf("Address of variable: %x\n", pointerToVariable);
printf("Address of variable: %x\n", *pointerToVariable); // * is the DEREFERENCING OPERATOR/INDIRECTION OPERATOR in C.
//It gives the value stored at the memory address
//stored in the variable which is its operand.
getchar();
return 0;
}
This produces the following output:
Address of variable: 8ffbe4
Address of variable: 8ffbe4
Address of variable: 14
But *pointerToVariable
should print 20, shouldn't it? Because *
gives the actual value stored at the memory address stored in its operand, right?
What am I missing?
14
is the HEX
value of 20
.
Change printf
format specifier to %d
instead of %x
to have 20
as output
printf("Address of variable: %d\n", *pointerToVariable);
Moreover correct format specifier for pointers is %p
, so
printf("Address of variable: %x\n", pointerToVariable);
must be
printf("Address of variable: %p\n", (void *)pointerToVariable);