Home > database >  Why the result of this code is duplicated?
Why the result of this code is duplicated?

Time:07-15

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:

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

CodePudding user response:

The point of the exercise is to show how a union works. The posted code does not do what the assignment asked, and here is the corrected code.

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

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

int main(void)                                           // conforming
{
   union family_name Family;        
   strcpy( Family.first_name, "Monjed");                 // write first member
   printf( "Last name : %s\n", Family.last_name);        // read second member
   printf("Size of union = %zu bytes", sizeof(Family));  // correct format spec
   return 0;
}

This shows that the data is shared by both members, and the size of the union is the size of its largest member.

Last name : Monjed
Size of union = 30 bytes

CodePudding user response:

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).

  •  Tags:  
  • c
  • Related