IHYPRESS PROGRAMMING
Tutorials and C programs with code and output for beginners
c programming
HOME | ASP | C | CSS | GNUPLOT | HTML | JAVASCRIPT | PERL | PHP | PYTHON | RUBY | SVG
CStructures & Linked Lists : Structure & Union Types
<10.08>
/* differences between structure and union */ #include <stdio.h> #include <string.h> /* defining a structure type */ typedef struct struct_example { int ni; double nd; char id[20]; }str; /* defining an union type */ 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"}; /* initial values */ 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); /* sizes */ printf("\nsizeof structure : %d\n", (int)sizeof(s)); printf("sizeof union : %d\n", (int)sizeof(u)); /* new values in structure */ 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); /* new values in union */ 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); /* one at a time is ok! */ 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); }
Hergestellt in Deutschland / Made in Germany
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
COPYRIGHT © 2015-2024 IHY PRESS Frankfurt am Main 60329 Deutschland