What will be output of the following program? Assume that you are running this…

2016

What will be output of the following program? Assume that you are running this program in little-endian processor.

C
#include<stdio.h>

int main() {
    short a = 320;
    char * ptr;
    ptr = (char * ) & a;
    printf("%d", * ptr);
    return 0;
}
  1. A.

    1

  2. B.

    320

  3. C.

    64

  4. D.

    Compilation error

Attempted by 314 students.

Show answer & explanation

Correct answer: C

The variable a is a short integer initialized to 320. In hexadecimal, 320 is represented as 0x0140.

On a little-endian system, the least significant byte is stored at the lowest memory address. Therefore, the bytes are stored as 0x40 followed by 0x01.

The pointer ptr is cast to a char pointer, pointing to the first byte (0x40). Dereferencing ptr gives the value 64 in decimal.

Explore the full course: Isro