#include <stdio.h>
#include <string.h>
typedef struct struct_example
{
int ni;
double nd;
char id[20];
}str;
typedef union union_example
{
int ni;
double nd;
char id[20];
}uni;
int
main(void)
{
str s = {100, 200, "structure 1"};
uni u = {100, 200, "union 1"};
printf("\nStructure data is: ni:%d nd:%0.2lf id:%s\n", s.ni, s.nd, s.id);
printf("Union data is: ni:%d nd:%0.0lf id:%s\n", u.ni, u.nd, u.id);
printf("\nsizeof structure : %d\n", (int)sizeof(s));
printf("sizeof union : %d\n", (int)sizeof(u));
s.ni = 300;
s.nd = 400;
strcpy(s.id, "structure 2");
printf("Structure data is: ni:%d nd:%0.0lf id:%s\n", s.ni, s.nd, s.id);
u.ni = 300;
u.nd = 400;
strcpy(u.id, "union 2");
printf("Union data is: ni:%d nd:%0.0lf id:%s\n", u.ni, u.nd, u.id);
u.ni = 500; printf ("%d ", u.ni);
u.nd = 600; printf ("%.0lf ", u.nd);
strcpy(u.id, "union 2"); printf ("%s ",u.id);
return (0);
}
main.c:27:19: warning: excess elements in union initializer
27 | uni u = {100, 200, "union 1"};
| ^~~
main.c:27:19: note: (near initialization for 'u')
main.c:27:24: warning: excess elements in union initializer
27 | uni u = {100, 200, "union 1"};
| ^~~~~~~~~
main.c:27:24: note: (near initialization for 'u')
Structure data is: ni:100 nd:200.00 id:structure 1
Union data is: ni:100 nd:0 id:d
sizeof structure : 40
sizeof union : 24
Structure data is: ni:300 nd:400 id:structure 2
Union data is: ni:1869180533 nd:0 id:union 2
500 600 union 2