]> Pileus Git - ~andy/sfvlug/blobdiff - c/src/struct.c
Add C notes.
[~andy/sfvlug] / c / src / struct.c
diff --git a/c/src/struct.c b/c/src/struct.c
new file mode 100644 (file)
index 0000000..1c67422
--- /dev/null
@@ -0,0 +1,79 @@
+#include <stdio.h>
+#include <stdint.h>
+
+int main()
+{
+       /*
+        * Structs
+        */
+       struct person {
+               char *name;
+               int   age;
+       };
+
+       struct person andy = { "Andy", 33 };
+
+       printf("%s is %d years old!\n",
+                       andy.name, andy.age);
+       printf("\n");
+
+       /*
+        * Typedefs
+        */
+       typedef struct {
+               char *name;
+               int   age;
+       } person_t;
+
+       person_t andys = { "Andy Spencer", 33 };
+
+       printf("%s is %d years old!\n",
+                       andys.name, andys.age);
+       printf("\n");
+
+       /*
+        * Pointers.
+        */
+       person_t *who = &andys;
+
+       printf("%s is %d years old!\n",
+                       (*who).name, (*who).age);
+
+       printf("%s is %d years old!\n",
+                       who->name, who->age);
+       printf("\n");
+
+       /*
+        * Unions.
+        */
+       union cake {
+               char *have;
+               char *eat;
+       };
+
+       union cake chocolate = {};
+
+       chocolate.have = "Yes please";
+       printf("Chocolate? %s!\n", chocolate.have);
+       chocolate.eat = "Yum";
+       printf("Chocolate? %s!\n", chocolate.eat);
+       printf("Chocolate? %s!\n", chocolate.have);
+       printf("\n");
+
+       /*
+        * Unions.
+        */
+       union types {
+               uint32_t number;
+               char     string[4];
+       };
+
+       union types abc = {
+               .string = "abc"
+       };
+
+       printf("Number: %08x\n", abc.number);
+       printf("String: %s\n",   abc.string);
+
+       return 0;
+}