Accessing Integer using char pointer : will Lose Binary Data !

Some Facts About Pointer Arithmetic :

  1. Pointer Always Stores to the memory address of the variable.
  2. De-Reference Means Accessing the data from the address being stored in pointer variable
  3. Asterisk(*) is used for De-Reference
  4. Memory occupied by pointer is same as memory occupied by integer variable

When Pointer is De-referenced then -

Pointer to the following type Number of Bytes accessed by Pointer
Integer Data Type 2 Bytes
Character Data Type 1 Byte
Float Data Type 4 Bytes

Live Example of Pointer Accessing :

Suppose we assign the address of integer variable to the character pointer then some part of value will be lost while accessing the variable using character data type.

#include<stdio.h>
int main()
{
int a=320;
char *ptr;
ptr=(char *)&a;
printf("%d",*ptr);
return(0);
}

Output of the Code :

64

Explanation of the above Code :

  1. Memory required to store integer and character is 2 bytes and 1 byte respectively
320 = 00000001  0100000
  1. Representation of 320 in Binary : 00000001 0100000
  2. If Pointer is of Integer type , It will Access both bytes (16 bits ) .
  3. As Pointer is of Character Type , as stated earlier in table it will access only one byte i.e ( 0100000 )
  4. 0100000 is nothing but the binary Representation of 64.
Binary Representation of 64 = 0100000