Hi all!!

See the following code:

#include <stdio.h>

int main()
{   
   union a
   {
        int i;
        char ch[2];
    };
    union a u;
    u.ch[0]=1;
    u.ch[1]=0;

   printf("%d   %d   %d\n",u.ch[0],u.ch[1],u.i);

  getch();    

return 0;    
}

The output that I get is:
1 0 2130509825

Why am I getting this number?

What I think the answer should be and why:

u.ch[0]=1 and u.ch[1]=0 means that the memory looks like-
10000000 00000000 00000000 00000000

As I am using windows, which is little endian (Am I wrong here?). This means that the field u.i should be 2^0=1, and not 2130509825.

Thanks in advance !!

Recommended Answers

All 3 Replies

How are your integers stored? Big or small endian? Also, are your integers 2 or 4 bytes?

Try something like below:

#include <stdio.h>

int main()
{
  size_t i = 0;
  union a
  {
    int i;
    char ch[sizeof(int)];
  };

  union a u;

  for (i = 0; i < sizeof(int); ++i)
  {
    if (i == 0) 
      u.ch[i] = 1;
    else
      u.ch[i] = 0;
  }

  printf("%d %d %d\n",u.ch[0],u.ch[1],u.i);

  return 0;
}

Awwwwwwwwww!!!!!!!

I understand. The byte 3 and byte 4 are not zeros as I assumed, they must be garbage. I assumed they would be all zeros because of the rule "if you initialize one member of a structure, others are initialized to 0 automatically". I thought this applied to unions also.

I added:

u.ch[2]=0;
and u.ch[3]=0;

and it outputs the following:

1 0 1

which is as expected.

Thanks !!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.