Structures are a group of related variables that are placed under one name. Unlike arrays, structures are not limited to one data type. The struct keyword will allow us to create a structure.
Below us is a brief example of a struct, with us printing out the information we assigned the struct to.
The keyword typedef allows us to create an “alias” of a previously defined data type. The capitalized “Animal” at the end of our struct allows us to use “Animal” as a variable declaration.
The “.”, known as the dot operator, is a structure member operator. When we create a struct, we the dot operator to access the information inside the struct.
We can make arrays out of structs too! The below code has an entire array of the Animal data type.
Just like other data types, structs can be created as pointers. This is used for linked lists, which will be discussed in a later blog post. When we use struct pointers, instead of the dot operator, we use “->”, which is known as the arrow operator.
Below is code to print out another zoo, but this time we are using pointers.
Zoo Pointer Code
There are other additions we need to use pointers. The stdlib contains important functions like malloc, malloc stands for “memory allocate”. Before memory allocation, the “zooptr” is pointing to a space in memory that hasn’t been allocated yet, which will cause a segmentation fault. After malloc has been called, space the size of the Animal struct has been allocated.
This is just an intro on how structures work. In the next blog post, we will go over how to create a linked list of structures, which is the basis for creating binary search trees, queues, stacks, and other “data structures”.