Consider the following c statement:
The above statement requests compiler to execute following steps:
- Reserve the required space (depending upon the data type and computer configuration) for the variable (randomly selected out of free memory pool)
- Assign i as name for that reserved space
- Store the integer value 2 in the reserved space
And we can find out the starting location number of that reserve space by the following statement:
printf (“Address is %u”, &x);
& operator is used find the address of the variable.
Suppose we get the output of the above statement as 8621 which is the starting address of the reserved space and hence we can represent the memory map for the variable i as:
if we run the same statement Int x=2; again then the same steps would be following but the memory location selected can be different from 8621. Reason being that the compiler randomly selects the location from the large pool of free memory spaces and every time we select it, there are rare chances of same memory location being selected.
Let’s see how memory spaces are managed. Suppose we have 0-9 byte locations in the free memory pool. Now whenever there is a request for the new memory space of 2 bytes then randomly starting address is chosen. Suppose selected location is 7. Hence memory locations 7 & 8 are taken out of free memory pool and shifted to used memory pool and then assigned the value. Now if another request is made, then we choose next space from the remaining pool of 0-6, 9 locations.
When ever the program is exited all the used memory is freed and again put into free memory space and hence are available for use again.
‘ * ’ operator is used to find the value at the address
Hence the statement given below prints the value 2 (i.e. value at the address &x)
printf(“value of x is %d”, *(&x));
If we assign &x to y as
Then the statement printf(“value of x is %d”, *y); prints 2 as output.
But we need to declare y as a variable to store the address of the variable and such a declaration is made as follow:
and variable y is called a pointer.