Monday, March 21, 2011

Program for Simple Pointers with Explanation


Program

#include <stdio.h>
main ()
{
   int i;         //A
   int * ia;      //B
   i = 10;        //C
   ia = &i;   //D

    printf (" The address of i is %8u \n", ia);          //E
    printf (" The value at that location is %d\n", i);   //F
    printf (" The value at that location is %d\n", *ia); //G
  *ia = 50;                                //H
    printf ("The value of i is %d\n", i);                //I
}

Explanation

  1. The program declares two variables, so memory is allocated for two variables. i is of the type of int, and ia can store the address of an integer, so it is a pointer to an integer.
  2. The memory allocation is as follows:
  3. i gets the address 1000, and ia gets address 4000.
  4. When you execute i = 10, 10 is written at location 1000.
  5. When you execute ia = &i then the address and value are assigned to i, thus i has the address of 4000 and value is 1000.
  6. You can print the value of i by using the format %au because addresses are usually in the format unsigned long, as given in statement E.
  7. Statement F prints the value of i, (at the location 1000).
  8. Alternatively, you can print the value at location 1000 using statement G. *ia means you are printing the value at the location specified by ia. Since i has the value for 1000, it will print the value at location 1000.
  9. When you execute *ia = 50, which is specified by statement H, the value 50 is written at the location by ia. Since ia specifies the location 1000, the value at the location 1000 is written as 50.
  10. Since i also has the location 1000, the value of i gets changed automatically from 10 to 50, which is confirmed from the printf statement written at position i.

No comments:

Post a Comment