-14

It is a question given in one of our placement Exams. explain the output of the following code...

#include <stdio.h>

int main(void)
{
   int i = 320;
   char *ptr = (char *)&i;
   printf("%d", *ptr);
   return 0;
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055

1 Answers1

6

You will get the numeric value of the "first" byte that makes up the int with value 320.

The precise output depends on the endianness of your platform:

  • Little-endian output: 64
  • Big-endian output: 0
  • Middle-endian output: god knows

Here are the octet-components of a 32-bit int on a little-endian, two's-complement system:

  • octet #0: 0x40
  • octet #1: 0x01
  • octet #2: 0x00
  • octet #3: 0x00

(An octet is an 8-bit byte. Your platform probably has octets as char, however more exotic platforms, with larger CHAR_BIT values, do exist.)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055