Reading¶
(1-2h) Study Chapter 10 including exercise 10.4 (p. 570) with the learning goals in mind. The following section/s is/are optional:
10.13 Secure C programming
In the following you also find my own notes.
Learning goals¶
Give an example where you would use a struct
Explain why a
structis usefulIdentify a struct declaration and its members
Define
typedef, union, and bitfields, andenumeration constants in one sentence eachRecognize a struct initializer and member access (
.and->) in example code.Identify an anonymous structure and union, and explain how it differs from a named one
10.1 Introduction¶
struct vs array
typedef: aliasesunions: like struct but share same storagebitfields: store data in one or more bits tightly
enumerations: sets of integer constants with a name
10.2 Structure Definition¶
struct Person {
char name[50];
int age;
float height;
};
struct Person person = {"Totoro", 49, 892.1};
person(Person &) @0x7cada7114000constexpr size_t MAX_WORD_COUNT = 64;
struct WordList {
char *words[MAX_WORD_COUNT];
size_t size;
};
struct WordList word_list;
word_list.size(unsigned long) 0Remember lines and line_count in Exercise 5, which described an array that tracks its runtime size. Now we can marry them 🧑🤝🧑 and pass them as a single parameter to a function.
Person and WordList are called tags.
Self-referential structures¶
struct Person2 {
char name[50];
unsigned age;
float height;
struct Person2 *mother;
};
struct Person2 person1 = {"Nature", 1u<<31, 10000, nullptr};
struct Person2 person2 = {"Totoro", 49, 892.1, &person1};
person2.name(char[50]) "Totoro"Used to build linked lists.
Defining struct variables¶
Similar to other datatypes:
constexpr size_t PERSON_COUNT = 16;
struct Person geko, persons[PERSON_COUNT], *current_person;
persons[5](Person &) @0x7cada710816cTagged or untagged¶
#include <stdint.h>
struct NetworkPacketBuffer {
uint32_t data[MAX_WORD_COUNT];
size_t size;
};
NetworkPacketBuffer receive_buffer, send_buffer;
receive_buffer.size(unsigned long) 0Tagged struct. We can use the tag to introduce other variables. Recommended.
#include <stddef.h>
struct {
uint32_t data[MAX_WORD_COUNT];
size_t size;
} receive_buffer2, send_buffer2;
receive_buffer2.size(unsigned long) 0Untagged struct — if we are sure we are not going to use it again.
Assignment¶
Structs do not decay to pointers like arrays, so we can do operations on the whole object.
puts("person1:");
printf("%s - %u - %.2f\n", person1.name, person1.age, person1.height);
puts("person2:");
printf("%s - %u - %.2f\n", person2.name, person2.age, person2.height);
person2 = person1;
puts("person2 now:");
printf("%s - %u - %.2f\n", person2.name, person2.age, person2.height);person1:
Nature - 2147483648 - 10000.00
person2:
Totoro - 49 - 892.10
person2 now:
Nature - 2147483648 - 10000.00Assignment copies whole object
person1.name(char[50]) "Nature"an existing struct
person1 = (Person2){};
person1.name(char[50]) ""Assign to zero
int arr[2] = {1, 2};
arr = {}/tmp/cell-tq43ywqc.repl:2:5: error: array type 'int[2]' is not assignable
2 | arr = {}
| ~~~ ^
error: Parsing failed.With arrays this was not possible.
person1 = (Person2){"Sima", 12, 100.0};
person1.name(char[50]) "Sima"Assign to multiple values
arr = {0, 1};/tmp/cell-0f3h469o.repl:1:1: error: use of undeclared identifier 'arr'
1 | arr = {0, 1};
| ^~~
error: Parsing failed.With arrays this was also not possible
Other operations:¶
sizeof&
Comparison is not allowed¶
person1 == person2/tmp/cell-3_201kax.repl:1:9: error: invalid operands to binary expression
('struct Person2' and 'struct Person2')
1 | person1 == person2
| ~~~~~~~ ^ ~~~~~~~
error: Parsing failed.We see that assignment is possible, but surprisingly not comparison. Why? On StackOverflow are some answers.
In short, C tries to keep things simple and efficient.
10.3 Initialization¶
Similar to arrays
#include <stdint.h>
struct Pixel {
uint8_t r, g, b;
};
struct Pixel white = {255, 255, 255};
(unsigned) white.r(unsigned int) 25510.4 Accessing members¶
.->(indirection and member access) because we often work with pointers to larger objects in C. Same as(*ptr).member
(unsigned) white.r(unsigned int) 255struct Pixel *pixel_ptr = &white;
(unsigned) pixel_ptr->r(unsigned int) 25510.5 Using with functions¶
whole struct without need for pointers (pass by value)
we can also just pass a member
pointer
Wrap an array with a struct to pass it by value:
struct CalibrationValues {
int values[MAX_WORD_COUNT];
};
int set_last_element(struct CalibrationValues cv) {
return cv.values[MAX_WORD_COUNT-1] = 100;
}
struct CalibrationValues cvalues;
set_last_element(cvalues)(int) 100set_last_element gets a copy (pass by value), so it only modifies a copy of the struct (and array).
cvalues.values[MAX_WORD_COUNT-1](int) 0The array in the outer scope is not modified.
10.6 typedef¶
To create synonyms for other types. For example size_t is actually a typedef:
Searching for size_t in the header files of clang:
grep size_t "$(clang -print-resource-dir)/include/__stddef_size_t.h"Outputs:
...
typedef __SIZE_TYPE__ size_t;Searching for __SIZE_TYPE__ constant
echo | clang -dM -E - | grep __SIZE_TYPE__#define __SIZE_TYPE__ long unsigned inttypedef struct {
uint8_t r, g, b;
} Pixel2;
Pixel2 pixel2;
pixel2(Pixel2 &) @0x7cada6a2e000Shorter than struct Pixel. We don’t need the tag name when we use typedef.
10.7 Random-number simulation case study¶
Now we can define a card structure and create a synonym with typedef:
struct card {
const char *face, *suit;
};
typedef struct card Card;First struct card and then typedef
typedef struct {
const char *face, *suit;
} Card;Direct typedef with untagged struct
10.8 Union¶
Compared to struct, members of the union share the same memory:
typedef struct {
double a;
char b;
} S1;
S1 s1;
printf("a @ %p\nb @ %p", &s1.a, &s1.b);a @ 0x7cada6a2a000
b @ 0x7cada6a2a008typedef union {
double a;
char b;
} S2;
S2 s2;
printf("a @ %p\nb @ %p", &s2.a, &s2.b);a @ 0x7cada6a26000
b @ 0x7cada6a26000similar to
structs, no comparison allowed.initialization uses the first datatype
Useful for data should be interpreted differently based on the scenario or has two different many of accessing the same data, see Figure 18.
For other examples: StackOverflow.
10.9 Bitwise operators¶
&,|,^xor,<<,>>,~&=,|=, etc
Often used to read-write to hardware registers, e.g., in a microcontroller like ATmega4808. Assume you want to set the direction of two pins as output using the Data Direction Set register:
PORTB.DIRSET = PIN0_bm | PIN1_bm;PIN0_bm is 0x01, PIN1_bm 0x02 etc. Using |, we get ...0011.
Another example: to display the bits of an integer by shifting a 1 gradually using << and masking using & operator.
10.10 Bit fields¶
Used to pack data tighter.
typedef struct {
uint32_t red : 8;
uint32_t green : 8;
uint32_t blue : 8;
} Color;
Color color;
color.red(unsigned int) 0We can also declare variables with exact number of bits: _BitInt() in C23 for exact bit amount specification
#include <stdio.h>
unsigned _BitInt(2) two_bits = 3uwb; // wb stands for _BitInt
int main() { printf("%u", (unsigned)++two_bits); }3 + 1 should give 0 with only two bits.
0Indeed 0.
10.11 Enumeration constants¶
We can assign our own values
typedef enum {
JAN1, FEB1, MAR1 // ...
} Month1;
Month1 month1 = JAN1;
month1(Month1) (JAN1) : unsigned int 0Without any explicit values
typedef enum {
JAN2 = 1, FEB2, MAR2 // ...
} Month2;
Month2 month2 = JAN2;
month2(Month2) (JAN2) : unsigned int 1With explicit value/s
We can also set the data type:
typedef enum : char {
JAN3 = 1, FEB3, MAR3 // ...
} Month3;
Month3 month3 = JAN3;
month3(Month3) (JAN3) : char 1With explicit value/s
10.12 Anonymous structures and unions¶
A C11 feature.
struct S {
int a, b;
struct {
double c, d;
};
};
struct S s;
s(S &) @0x7cada6a12000Useful in unions and tagged unions
union {
struct {
double x;
double y;
double z;
};
double raw[3];
} vector3;
vector3.raw(double[3]) { 0.0, 0.0, 0.0 }Figure 18:struct with x, y, z is anonymous. The struct and raw are alternative views to data
typedef struct {
bool is_float;
union {
float f;
char* s;
};
} FloatOrCharPtr;
double as_float(FloatOrCharPtr *focp)
{
if (focp->is_float) return focp->f;
else return atof(focp->s);
}
FloatOrCharPtr focp;
focp.is_float = true;
as_float(&focp)(double) 0.0A tagged union that can read data as a string or float.
Credits: StackOverflow
10.13 Secure Programming¶
structs:
size is not necessarily the sum of the total size of its members due to alignment
undefined areas in struct can contain sensitive data from previous operations
typedef:
use typedef for complex datatypes like function pointers
bit manipulation
due to bit promotion rules, performing bitwise operations on types smaller than int can cause problems.
number literals are integers as default in C
bitwise operators on signed types are compiler dependent. Use unsigned.
&&and&confused with||and|.
Binary literals¶
Not covered in the book.
Similar to octals and hexadecimals.
0b100(int) 4Printing:
printf("%b", 0b100);100Raylib¶
Installation¶
You can follow the text instructions or/and screencast.
Screencast¶
Screencast of installation & running
Text instructions¶
Go to the latest Raylib release.
Scroll down to
Assets:
Under Assets, download the package
raylib-*_win64_mingw-w64.zipRight-click the file, and click Extract All.
Click Browse:

Select your
codefolder. If you followed the Folder structure for the semester, the path should look similar to:
Example path to your code folder.
Expected folder layout:
... 📁 code ├── 📁 EXTRACTED-RAYLIB-FOLDER ├── 📁 repository1 ├── 📁 repository2 ├── 📁 ...Click Extract. The extracted folder will be shown.
Rename the
raylib-*folder toraylib, so you get the following layout:... 📁 code ├── 📁 raylib ├── 📁 repository1 ├── 📁 repository2 ├── 📁 ...
Open a terminal and:
brew install raylibIn the assets, the package raylib-*_winarm64_msvc16.zip is probably not going to work and you have to compile the library yourself. https://
Running Raylib template¶
Clone our Raylib template https://
github .com /dtucprog /c -template -multi -raylib Click
raylib_hello.cand run it using F5. You should see:
Congratulations 💯
Appendix¶
Mimicking inheritance using structs¶
C does not support object-oriented programming and thus inheritance. First I thought we can do something similar with anonymous structures, because if an anonymous struct or union is added, then their items are appended at the same level. However the left example does not work and we have to provide a name to base a new struct on another tagged struct:
struct Vehicle {
char *name;
double speed;
};
struct ElectricVehicle {
struct Vehicle; // <- IGNORED BY COMPILER
double battery_capacity;
};
struct ElectricVehicle ev1;
ev1.name // <- LEADS TO ERRORstruct Vehicle {
char *name;
double speed;
};
struct ElectricVehicle {
struct Vehicle base;
double battery_capacity;
};
struct ElectricVehicle ev1;
ev1.base.name(char *) 0