Programming in C: Structures

A structure in C provides us with a way of storing many different values in variables of potentially different types under the same name. Using structures makes a program more modular, allowing for easier modification, reuse, and allows the code to be more compact.

Structs are generally useful whenever a lot of data needs to be grouped together, for example contacts in an address book. A single entry in an address book needs a name, number, address, and more. A struct makes this very easy for us to do.

Here is the general syntax of a struct:

struct Tag 
{
Members
};

Tag represents the name of the structure and the members are the variables within it. To actually create a single structure and access a members data:

/* Shows the general syntax of create a structure with a name */
struct Tag structure_name;

/* Shows how to access a member of a single struct */
structure_name.variable_name;

Here is an example:

struct database 
{
int id_number;
int age;
float salary;
};

int main()
{
/* There is now an employee variable that has
modifiable variables inside it.*/
struct database employee;

employee.age = 25;
employee.id_number = 10001;
employee.salary = 27387.25;

return 0;
}

The struct database has three variables, age, id_number, and salary. You can use database like a variable type and create an employee with the database type as seen above. The employee then has the three attribute listed above. To change the values of the three variables use the '.' operator.

Finally, you can have a pointer to a struct, as seen in the example below. To access the information stored inside the structure we then use the '->' operator in place of the '.' operator.

#include <stdio.h>

struct example {
int x;
};

int main()
{
struct example structure;
struct example *ptr;

structure.x = 12;
/* Yes, you need the & when dealing with 
 structures and using pointers to them*/
ptr = &structure; 
/* The -> acts somewhat like the * when 
does when it is used with pointers
It says, get whatever is at that memory
address Not "get what that memory address is"*/
printf( "%d\n", ptr->x );
return 0;
}

If you have any suggestions of tutorials or any specific topics you want to see covered, please leave a comment below and I will take your suggestions into consideration. Follow me on Twitter to keep up-to-date on all the latest news and tutorials.

Programming in C: Pointers