0

I am a college student and currently a beginner in C language. I would like to know how many bytes the following union types occupy. I asked ChatGPT, but its answer confused me. On my computer, your textdata of type int takes up four bytes. Thank you very much!

main()
{
  union pw
  {
     unsigned char c;
     unsigned int i[4];
  }z;

  z.i[0] = 0x39;
  z.i[1] = 0x36;
  printf("%c\n", z.c);
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 3
    `printf("%zu\n", sizeof(z));` should give the answer – Ted Lyngmo Mar 16 '23 at 12:57
  • 4
    "I asked ChatGPT," Don't do this. Programming questions can barely be answered using language statistics. – Gerhardh Mar 16 '23 at 12:59
  • @Gerhardh: The answer in the title is incorrect. The typical size of `union { int i; char c[13]; }` is not the size of its largest member. – Eric Postpischil Mar 16 '23 at 13:32
  • @EricPostpischil That's the answer ChatGPT gives initially. But if you show it your counterexample, it corrects itself and explains why the initial answer was wrong. An impressive machine, that. – n. m. could be an AI Mar 16 '23 at 13:52
  • @EricPostpischil you're right. the padding could also be caused by smaller members. – Gerhardh Mar 16 '23 at 14:35
  • 2
    Your style of main definition is dated back more than 30 years ago. You should change it so that it explicitly returns int and either accepts zero or two arguments. Currently it can accept any number of arguments. – SafelyFast Mar 16 '23 at 16:42

0 Answers0