Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How values are changed in C unions?

#include <stdio.h>

int main()
{
 typedef union{
     int a ;
     char c;
     float f;
 } myu;
 
 myu sam;
 sam.a = 10;
 sam.f=(float)5.99;
  sam.c= 'H';

 printf("%d\n %c\n %f\n",sam.a,sam.c,sam.f);
 return 0;
}

Output

1086303816

H

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

5.990025

How come the value of integer has changed so drastically while the float is almost the same.

>Solution :

Try this. Instead of using printf (which will mainly output nonesens) show the raw memory after each modification.

The code below assumes that int and float are 32 bit types and that your compiler does not add padding bytes in this union.

#include <string.h>
#include <stdio.h>
#include <assert.h>

void showmemory(void* myu)
{
  unsigned char memory[4];
  memcpy(memory, myu, 4);

  for (int i = 0; i < 4; i++)
  {
    printf("%02x ", memory[i]);
  }
  printf("\n");
}

int main()
{
  typedef union {
    int a;
    char c;
    float f;
  } myu;

  assert(sizeof(myu) == 4);  // assume size of the union is 4 bytes

  myu sam;
  sam.a = 10;
  showmemory(&sam);

  sam.f = (float)5.99;
  showmemory(&sam);
 
  sam.c = 'H';
  showmemory(&sam);
}

Possible output on a little endian system:

0a 00 00 00      // 0a is 10 in hexadecimal
14 ae bf 40      // 5.99 in float
48 ae bf 40      // 48 is 'H'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading