Being able to know where in RAM your data is stored comes in handy very often. The most obvious situation is when you want to request a block of memory from the system, use it only temporarily, and then return it to the system for reuse for some other purpose. This is called dynamic memory allocation.
To understand how this works, you need to know about pointers. A pointer is an address of an item of data in RAM. In C, a pointer takes up four (4) bytes using the Linux OS. It doesn't matter what kind of data is being pointed to, e.g., char, int, or double, which themselves are one, four, and eight bytes in size; all pointers are the same size.
Suppose we have two short int variables and a short int pointer variable declared as follows:
short int x, y; short int *sint_ptr;
These declarations request two bytes of RAM each for x and y, and four bytes for sint_ptr. The splat (*) indicates that sint_ptr is a pointer.
The following statements do two things: The first assigns the value 2 to x and the second, using the address of operator, the ampersand (&), stores the address of x in the pointer variable sint_ptr.
x = 2; sint_ptr = &x;
Until an assignment such as the second is made, sint_ptr will be pointing at some random location, but frequently at address zero. Using this variable to store a value would result in incorrect results or even cause the program to crash. Once the second assignment has been made, the following two statements are equivalent:
printf("%d\n", x);
printf("%d\n", *sint_ptr);
The indirection (dereferencing) operator (*) indicates that the item pointed at by sint_ptr is the one that is to be printed. Since it points at x, both calls to printf() will result in the value 2 being printed.
It is also possible to use data pointed at by a pointer variable in an expression. The following statements result in the value 4 being assigned to y:
x = 2; y = *sint_ptr + x;
This is clearly not the best way to use a pointer, but it illustrates what is possible.
The pointer variable can be used to make an assignment to the item that it points to. The following two assignments are equivalent:
x = 2; *sint_ptr = 2;
Here is one last simple example. As you know, scanf() requires addresses for the variables that data is to be read into. The following two statements would both read data from the keyboard into x:
scanf("%d", &x);
scanf("%d", sint_ptr);