Using char array inside union

前端 未结 3 2121
情歌与酒
情歌与酒 2020-12-15 01:30

I\'m able to print the address and values of ints but not the chars of the union.Why is that so

#include 

using namespace std;

union Endian         


        
3条回答
  •  Happy的楠姐
    2020-12-15 01:43

    Strictly speaking, the behaviour of your code is undefined. Contrary to what I said earlier, the behaviour of the code is not undefined (I think it's implementation-defined). See https://stackoverflow.com/a/1812932/367273 for an explanation.

    What happens is that &e.c[0] is of type char*, and therefore gets printed as a C string, not as a pointer. The string is either blank or consists of non-printable characters, so you see no output. A similar thing happens to e.c[1], except that it's a single char and not a string.

    When I initialize e as follows:

    e.i = 0x00424344;
    

    the last two lines print DBC and B respectively (this exploits the fact that on my machine, int 32 bits wide and is little-endian).

提交回复
热议问题