What's up, peeps? In this quick tutorial, we will be looking at structs, a special kind of data type.
A structure, or just struct, is a user-defined data type where we are able to group multiple variables together to form a convenient package. Why would we want to do this? A struct provides a managed container which serves to hold items which are common to each other to represent a whole object. For example, a person has many attributes such as names, gender and age. Let's see it in code.
To define a struct, we require the struct keyword followed by an identifier, _person in our case. I've used a typedef here to define the entire struct with our own data type keyword Person to make things a little easier. If you don't wish to do this, you will need to use struct _person as the data type to define a variable of the struct. Inside our struct definition, we have what we call members which are our grouped variables. Note that we do not initialize our variables inside the definition but just define them like we would in a function definition. Oh, and don't forget the semicolon after the struct!
In main, we declare a type Person (struct _person) and name it Moe, and to initialize it, we call a function newPerson and give it parameters. In newPerson, we see how we can individually access and initialize each member of a struct by using the variable name with a dot followed by the struct's member name.
We then call printf to print each of the members of Moe.
Note: The \t is a special character for a tab. Just for little visual formatting.
As we can see, structs are neat and they allow us to combine common items together which can be of any data type including other structs. Many libraries utilize these structs to organize things together as we will see later, so it's good to know how to use them.
Start your White-Hat Hacker journey with Null Byte's Beginner's Guide to Mastering Linux eBook.