EmbLogic's Blog

c: JATINDER KUMAR

#include

static unsigned char h[5] = {1,2,3,4,5};

int main()
{
struct ad
{
unsigned short a;
unsigned short b;
};
struct ad *it;

it = (struct ad *)h;

printf(“%d “,it->a);
printf(“%d “,it->b);
}
what will be the output and whyu????

4 Responses to c: JATINDER KUMAR

  1. zahid says:

    Ans: 513 1027
    Reason: first it -> a read initial 2 bytes from char array h[] which is
    0000 0010 0000 0001 => (513) base 10
    ——— ———
    2 1

    similarly for 1027:
    read next 2 bytes

    0000 0100 0000 0011 => (1027) base 10
    ——— ———
    4 3

  2. could ypu plrease elaborate

    • msiddarth says:

      You can’t just cast an array to a structure because they’re simply incompatible types. Due to memory alignment constraints, the compiler needs to insert padding between the fields of a structure, so the members are not located at the memory addresses you may expect. Solutions:

      Portable but slower/harder to do manually (preferred): copy manually the fields of the structure to the array.
      Shorter to write but GCC-specific: use the __attribute__((packed)) keyword to make GCC not introduce padding between struct fields.

  3. ritesh says:

    short integer is of 2 byte.. we have stored the add of char array in structure which contain two member of unsigned short type.. so lt->a will pick the first two bytes of your character array which is ch={1,2,3,4,5}
    so lt->a will points to 1st two byte which contains integer value 1,2 and bit representation of these two is
    00000010 00000001 and converting into decimal will give you 513 and similarly lt->b will take next two integer 3,4 and bit representation is 00000100 00000011=1027

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>