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