]> Pileus Git - ~andy/sfvlug/blob - c/src/struct.c
Add C notes.
[~andy/sfvlug] / c / src / struct.c
1 #include <stdio.h>
2 #include <stdint.h>
3
4 int main()
5 {
6         /*
7          * Structs
8          */
9         struct person {
10                 char *name;
11                 int   age;
12         };
13
14         struct person andy = { "Andy", 33 };
15
16         printf("%s is %d years old!\n",
17                         andy.name, andy.age);
18         printf("\n");
19
20         /*
21          * Typedefs
22          */
23         typedef struct {
24                 char *name;
25                 int   age;
26         } person_t;
27
28         person_t andys = { "Andy Spencer", 33 };
29
30         printf("%s is %d years old!\n",
31                         andys.name, andys.age);
32         printf("\n");
33
34         /*
35          * Pointers.
36          */
37         person_t *who = &andys;
38
39         printf("%s is %d years old!\n",
40                         (*who).name, (*who).age);
41
42         printf("%s is %d years old!\n",
43                         who->name, who->age);
44         printf("\n");
45
46         /*
47          * Unions.
48          */
49         union cake {
50                 char *have;
51                 char *eat;
52         };
53
54         union cake chocolate = {};
55
56         chocolate.have = "Yes please";
57         printf("Chocolate? %s!\n", chocolate.have);
58         chocolate.eat = "Yum";
59         printf("Chocolate? %s!\n", chocolate.eat);
60         printf("Chocolate? %s!\n", chocolate.have);
61         printf("\n");
62
63         /*
64          * Unions.
65          */
66         union types {
67                 uint32_t number;
68                 char     string[4];
69         };
70
71         union types abc = {
72                 .string = "abc"
73         };
74
75         printf("Number: %08x\n", abc.number);
76         printf("String: %s\n",   abc.string);
77
78         return 0;
79 }