Clark Bell Clark Bell - 2 months ago 15
C Question

Demonstration of Virtual Memory with C

#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.

Answer

First of all, you should familiarize yourself with the concept of a pointer. Fortunately there are loads of great references out there like this (The first 5 sections are what is important).

After doing some pointer reading, the bottom line is that & is an operator in C that returns the address of the variable it precedes. (It actually can have two uses depending on the context it is used in, the other is a bitwise AND operator, but you shouldn't worry about that until you need to use it).

Also, you should always use %p to print out a pointer. The reason is because it makes your code more portable to different operating systems.

 printf("Address: %p\n", (void*) &staticVar);

This code will work, however I would not cast to a void pointer, because that typecast is unnecessary and makes the code less readable. Try this instead.

 printf("Address: %p\n", &staticVar);