Thursday 31 March 2011

Memory Addresses

When you declare a variable of any type, memory is taken up. Each variable then has what is called a "memory address" which is an indication of where it is stored in memory. The memory address of any variable is indicated in hexadecimal (or honestly, some other number base, it may be octal, but that's not really important for now). Accessing the memory address of any variable is easy.

int x;

&x  //is the memory address of x

So you may be asking yourself why you would ever need to know things like this.
WELL
A simple application in which you're basically required to use memory addresses is the use of  scanf().
scanf() can be thought of doing the opposite of printf(). Instead of outputting information to the user, it takes information from the user and stored it in variables. Here's how we would ask the user to store a value for an integer x;

int x;
printf("Input a value for x: ");
scanf("%d",&x);


Notice how the format string for scanf() is exactly the same as printf(). The main difference here is that the second parameter is asking "where do you want to store this value". The obvious answer is "in x," but really, you're going to want to be storing it in the space that x is occupying in memory - its memory address. Also notice how we cannot print to the screen using scanf. In order to let the user know what he is supposed to input, we must use printf() to print instructions as the program executes.

3 comments:

  1. informative and entertaining. a rare combination.

    ReplyDelete
  2. Really helpful stuff. I'll get there eventually...
    Thank you for this!

    ReplyDelete