Search code examples
cpointersoutputdereference

Ambiguous Output generated using Pointer dereferencing?


I encountered a following program and was not able to understand how is the output coming to be -109 1683.How is the output coming out to be so?

 #include <stdio.h>

 int main()
{
 int k = 1683;
 char *a = (char *)&k;
 int *l  = &k;
 printf("%d " , *a);
 printf("%d" , *l);
  }
 Output is : -109 1683

How does dereferencing the pointer a give me -109?

I expected it to read first byte of the four byte integer .

1683 in binary representation is 00000000 00000000 00000110 10010011.So reading first byte means output should be 0 1683. What is happening behind the scenes , I heard something concerning to architecture endianness , but could not able to follow it.


Solution

  • If you have something like ,

    int k = 1683 ;
    int *l = &k;
    

    If You Dereference Pointer l then it will correctly read integer bytes. Because You declared it to be pointer to int . It will know how many bytes to read by sizeof() operator. Generally size of int is 4 bytes (for 32/64-bit platforms) but it is machine dependent that is why it will use sizeof() operator to know correct size and will read so .Now For Your Code

     int k = 1683;
     char *a = &k;
     int *l  = &k;
    

    Now pointer p points to y but we have declared it to be pointer to a char so it will only read one byte or whatever byte char is of . 1683 in binary would be represented as

            00000000 00000000 00000110 10010011

    Now if your machine is little endian it will store the bytes reversing them

            10010011 00000110 00000000 00000000

    10010011 is at address 00 Hypothetical address , 00000110 is at address 01 and so on.

    BE:      00   01   02   03
           +----+----+----+----+   
        y: | 00 | 00 | 06 | 93 |
           +----+----+----+----+
    
    
    LE:      00   01   02   03
           +----+----+----+----+
        y: | 93 | 06 | 00 | 00 |
           +----+----+----+----+
    
    (In Hexadecimal)
    

    So now if you dereference pointer a it will read only first byte and output will be -1 as byte read would be 10010011(Because we pointed signed char ,so the most-significant bit is the sign bit. First bit 1 denotes the sign. 10010011 = –128 + 16 + 2 + 1 = –109.) and if you dereference pointer l it will completely read all bytes of int as we declared it to be pointer to int . And output will be 1234

    And Also if you declare pointer l as int *l then *l will read sizeof(int) usually 4 bytes(Depends On Machine Architecture) and *(l+1) will also read that many bytes . Same goes with char or any other data type the pointer pointed to them will read as many bytes there size is of , char is of 1 byte.