Search code examples
arrayscstructure

Why isn't the output right?


union test
{
int x;
char arr[4];
int y;
};

#include<stdio.h>
int main()
    {
    union test t;
    t.x = 0;
    t.arr[1] = 'G';
    printf("%s", t.arr);
    return 0;
    }

Predict the output of the above program. Assume that the size of an integer is 4 bytes and size of a character is 1 byte.

Why shouldn't the answer be Garbage character followed by 'G', followed by more garbage characters?


Solution

  • Assuming 4 byte ints here:

    t.x = 0;
    

    write four 0 bytes into the union. That overwrites all the elements in arr[].

    t.arr[1] = 'G';
    

    writes a 'G' into the second byte of the union. There are still 3 zero-bytes: one before the G and two after the G.

    printf("%s", t.arr);
    

    prints up to the first 0 byte in t.arr, which is the first byte in t.arr because you wrote 4 zeroes into the union. No output.