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

Why the result of this code is duplicated?

Why the result is duplicated

Hi, I made this code and what I want is Create Union type called family_name it shall have two members first_name and last_name. The two members are array of characters with same size 30. Try to write string in the first member
first_name, then print the second member last_name also print the size of the union.

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

union family_name
{
   char first_name[30];
   char last_name[30];
};

int main( )
{
   union family_name Family;        

   strcpy( Family.first_name, "Monjed");
   strcpy( Family.last_name,  "Salih");

   printf( "First name : %s\n", Family.first_name);
   printf( "Last name : %s\n", Family.last_name);
   printf("Size of union = %d bytes", sizeof(Family));


   return 0;
}

Result:

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

 First name : Salih
 Last name : Salih
 Size of union = 30 bytes

>Solution :

you need to use structure instead of union.

struct family_name
{
   char first_name[30];
   char last_name[30];
};

union members share the same memory (ie will have the same context in your case as you have the same type of members).

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