How To: Security-Oriented C Tutorial 0x17 - Structs

Security-Oriented C Tutorial 0x17 - Structs

What's up, peeps? In this quick tutorial, we will be looking at structs, a special kind of data type.

What Is a Struct?

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.

Example 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.

Compiling and Running

Looks good!


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.


Want to start making money as a white hat hacker? Jump-start your hacking career with our 2020 Premium Ethical Hacking Certification Training Bundle from the new Null Byte Shop and get over 60 hours of training from cybersecurity professionals.

Buy Now (90% off) >

Other worthwhile deals to check out:

Join the Next Reality AR Community

Get the latest in AR — delivered straight to your inbox.

Be the First to Comment

Share Your Thoughts

  • Hot
  • Latest