Sunday, 21 April 2013

Accessing Integer through character pointer

#include<stdio.h>
int main()
 {   
  int i=512;   
  char *c =(char*)&i;  
  c[0]=2;   
  printf("%d",i);   
  return 0;
 }



Explanation:
The answer is given assuming that your system is Big-endian. For details about endianness you can check this.
  
    0   1   2   3   4   5   6   7        8   9  10  11  12  13  14  15
  +---+---+---+---+---+---+---+---+    +---+---+---+---+---+---+---+---+
  | 0 |0  |0  |0  |0  |0  |0  | 0 |    |0  |1  |0  |0  |0  |0  |0  |0  |
  +---+---+---+---+---+---+---+---+    +---+---+---+---+---+---+---+---+

 
This is the last two byte (0th and 1st) representation of i. When we are assigning i to c, c points to the base address of the i but when we will try to access c we will not get the whole of i at a time as c is a character pointer. So c means only the first 1 byte of i. Similarly c[0] is also points to the first byte of i. So when assigning 2 to c[0] it means it just updating the first byte and 2nd bit of the first bit will be set to 1. Now when we will print the value of i then we will get a value 512+2=514.

No comments:

Post a Comment