I remember being in school back around 1998 and not knowing enough about C to do this. After coding in other languages, then going back to C++ and understanding at a lower level how references and pointers work, this was pretty easy to figure out.
In this exercise I store elements of different types in a forward linked list.
In order to know what to dereference as I iterate through the list’s elements, I’ve put a “.type” field, which has an int value representing the type of the object stored.
The “.value” is simply a
void*, which lets me store a pointer of any kind, and it works pretty well.
Here’s the code for your enjoyment, I hope this is useful to C apprentices.
The example shows how you can store native types like int, or more complex
char* or even a
struct person* (which is the more useful probably to your purposes)
It’s a good exercise to see the uses of the “address of” operator “&”, which is used to initialize pointers (the ‘&’ can also be used differently to create references, which I call in my mind as ‘aliases’, but this is not shown in this example)
I also play with a not so popular syntax to access a pointer’s sub-fields:
(*myPointer).structField == myPointer->structField
to teach you that the
-> is a short hand for dereferencing a pointer and accessing one of its fields.
The output is this:
- INTEGER: 1 - STRING: anyfing, anyfing! - TYPE_PERSON: Angel (35) - BOOLEAN (true:1, false:0): 1