• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 208
  • Last Modified:

output question

Hello experts

I am unable to understand the logic behind the output (3 2 515)of the following program:

int main()
{
union a
{
int i;
char ch[2];
};
union a u;
u.ch[0]=3;
u.ch[1]=2;
printf("%d %d %d",u.ch[0],u.ch[1],u.i);
}

is it because of ascii values of 3 and 2?

thanks in advance:)
0
shilpi84
Asked:
shilpi84
2 Solutions
 
OnegaZhangCommented:
515 = 0x2 03
you know the fact that ch and i share the same memory. But it is dangerous in my opinion, since ch only use 2 bytes memory, but i is 4 bytes, so you are reading 2 bytes uninitialized memory when reading u.i
0
 
archang3lCommented:
Hello shilpi84,

If you convert 515 to hexademical it is 0x0203.
According to Intel byte order it would end up being 03 02.

This is the same as the values you are putting into the union, so it is not ascii values but rather you are building the integer byte by byte.

Regards,

archang3l
0
 
shilpi84Author Commented:
thanku very much:)
0

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now