output question

Posted on 2007-09-29
Last Modified: 2010-04-01
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;[0]=3;[1]=2;
printf("%d %d %d",[0],[1],u.i);

is it because of ascii values of 3 and 2?

thanks in advance:)
Question by:shilpi84
    LVL 12

    Accepted Solution

    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
    LVL 10

    Assisted Solution

    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.



    Author Comment

    thanku very much:)

    Featured Post

    Maximize Your Threat Intelligence Reporting

    Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

    Join & Write a Comment

    Article by: SunnyDark
    This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
    Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
    The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
    The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

    730 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now