Home > Mobile >  code that gives different values on different online compilers
code that gives different values on different online compilers

Time:09-23

I have a code that gives different values on different online compilers, I am new to C programming, please let me know if different values are expected while we run the following code on different c online compilers:

#include <stdio.h>
struct hai
{
    char c;
    long l;
    char *p;
};
union bye
{
    char c;
    long l;
    char *p;
};
int main (int argc, char *argv[])
{
    struct hai myhai;
    union bye mybye;
    myhai.c = 1;
    myhai.l = 2L;
    myhai.p = "This is myhai";
    mybye.c = 1;
    mybye.l = 2L;
    mybye.p = "This is mybye";
    printf("myhai: %d %ld %s\n", myhai.c, myhai.l, myhai.p);
    printf("mybye: %d %ld %s\n", mybye.c, mybye.l, mybye.p);
    return 0;
}

CodePudding user response:

Union is the place where members share the same memory location. Union has only storage enough for the largest member of it.

Writing any of members overwrites at least the part of the memory occupies by other members.

In your case the at write is important. It stores the address of the string literal into the union. When you read the c member you read the first byte of this address.

CodePudding user response:

In a union the fields are overlayed. Exactly how is undefined:

  • Little endian and big endian play a role, both can have the fields aligned at offset 0, but other byte values reside there. (LE = least significant byte first: 257 = 02 01; BE = most signifact byte first: 257= 01 02
  • The struct is not zeroed, so after assigning a char, the long will contain rubish, and the char likely is the least or most significant byte.
  •  Tags:  
  • c
  • Related