Tuesday, 30 June 2015

Example To Demonstrate Working of Pointers

#include <stdio.h>
int main(){
   int* pc;
   int c;
   c=22;
   printf("Address of c:%d\n",&c);
   printf("Value of c:%d\n\n",c);
   pc=&c;
   printf("Address of pointer pc:%d\n",pc);
   printf("Content of pointer pc:%d\n\n",*pc);
   c=11;
   printf("Address of pointer pc:%d\n",pc);
   printf("Content of pointer pc:%d\n\n",*pc);
   *pc=2;
   printf("Address of c:%d\n",&c);
   printf("Value of c:%d\n\n",c);
   return 0;
}

Output
Address of c: 2686784
Value of c: 22

Address of pointer pc: 2686784
Content of pointer pc: 22

Address of pointer pc: 2686784
Content of pointer pc: 11

Address of c: 2686784
Value of c: 2
Working of pointers in C programming
Explanation of program and figure
  1. Code int* pc; creates a pointer pc and a code int c; creates normal variable c. Pointer pc points to some address and that address has garbage value. Similarly, variable c also has garbage value at this point.
  2. Code c=22; makes the value of c equal to 22, i.e.,22 is stored in the memory location of variable c.
  3. Code pc=&c; makes pointer, point to address of c. Note that, &c is the address of variable c (because c is normal variable) and pc is the address of pc (because pc is the pointer variable). Since the address of pc and address of c is same, *pc will be equal to the value of c.
  4. Code c=11; makes the value of c, 11. Since, pointer pc is pointing to address of c. Value inside address pc will also be 11.
  5. Code *pc=2; change the contents of the memory location pointed by pointer pc to change to 2. Since address of pointer pc is same as address of c, value of c also changes to 2.

Commonly done mistakes in pointers

Suppose, the programmer want pointer pc to point to the address of c. Then,
int c, *pc;
pc=c;  /* pc is address whereas, c is not an address. */
*pc=&c; /* &c is address whereas, *pc is not an address. */
In both cases, pointer pc is not pointing to the address of c.

No comments:

Post a Comment