#include <stdio.h>
#include <unistd.h>
int staticVar = 0;
int main()
{
staticVar += 1;
sleep(10);
printf("Address: %x\nValue: %d\n", &staticVar, staticVar);
return 0;
}
I'm confused how this program prints out the address of the variable "staticVar". From playing with the code I noticed that if you change the printf statement to this...
printf("Address: %x\nValue: %d\n", staticVar, staticVar);
Then the value of the variable "staticVar" is printed in the "Address" position.
Some quick research led me to understand that the addition of "&" meant that the variable "staticVar" was being referenced and that the "%x" in the printf statement prints out the value in hex. Even with this information I am still confused as to why this works.
I also read online that you can print out the address to some variable with this line...
printf("Address: %p\n", (void*) &staticVar);
Is there advantage to doing it this way?
I may just need an explanation to what the "&" symbol effectively does.