Monday, March 21, 2011

Program for Address and Pointers with Explanation


Program

#include <stdio.h>
main ()
{
    int i, j, k;      //A
            i = 10;           //B
    j = 20;           //C
    k = i + j; //D

    printf ("Value of k is %d\n", k);
}

Explanation

  1. Memory allocations to the variables can be explained using the following variables:
    100,i      10
    200, j     20
    300,k      30
    
    When you declare variables i, j, k, memory is allocated for storing the values of the variables. For example, 2 bytes are allocated for i, at location 100, 2 bytes are allocated for j at location 200, and 2 bytes allocated for k at location 300. Here 100 is called the address of i, 200 is called address of j, and 300 is called the address of k.
  2. When you execute the statement i = 10, the value 10 is written at location 100, which is specified in the figure. Now, the address of i is 100 and the value is 10. During the lifetime of variables, the address will remain fixed and the value may be changed. Similarly, value 20 is written at address 200 for j.
  3. During execution, addresses of the variables are taken according to the type of variable, that is, local or global. Local variables usually have allocation in stack while global variables are stored in runtime storage.

No comments:

Post a Comment