Chapter 9 - Structures
Arrays and Strings => Similar data (int, float, char)
Structures can hold => dissimilar data
Syntax for creating Structures
A C Structure can be created as follows:
We can use this user-defined data type as follows:
So a structure in c is a collection of variables of different types under a single name.
Quick Quiz: Write a program to store the details of 3 employees from user-defined data. Use the structure declared above.
Why use structures?
We can create the data types in the employee structure separately but when the number of properties in a structure increases, it becomes difficult for us to create data variables without structures. In a nutshell:
- Structures keep the data organized.
- Structures make data management easy for the programmer.
Array of Structures
Just like an array of integers, an array of floats, and an array of characters, we can create an array of structures.
We can access the data using:
..........and so on.
Initializing structures
Structures can also be initialized as follows:
Structures in memory
Structures are stored in contiguous memory locations for the structures e1 of type struct employee, memory layout looks like this:

In an array of structures, these employee instances are stored adjacent to each other.
Pointer to structures
A pointer to the structure can be created as follows:
Now we can print structure elements using:
Arrow operator
Instead of writing *(ptr).code, we can use an arrow operator to access structure properties as follows
*(ptr).code or ptr->code
Here -> is known as an arrow operator.
Passing Structure to a function
A structure can be passed to a function just like any other data type.
void show(struct employee e); =>Function prototype
Quick Quiz: Complete this show function to display the content of the employee.
Typedef keyword
We can use the typedef keyword to create an alias name for data types in c.
typedef is more commonly used with structures.
Chapter 9- Practice Set
- Create a two-dimensional vector using structures in C.
- Write a function SumVector which returns the sum of two vectors passed to it. The vectors must be two-dimensional.
- Twenty integers are to be stored in memory. What will you prefer- Array or Structure?
- Write a program to illustrate the use of an arrow operator -> in C.
- Write a program with a structure representing a Complex number.
- Create an array of 5 complex numbers created in problem 5 and display them with the help of a display function. The values must be taken as an input from the user.
- Write problem 5’s structure using typedef keyword.
- Create a structure representing a bank account of a customer. What fields did you use and why?
- Write a structure capable of storing date. Write a function to compare those dates.
- Solve problem 9 for time using typedef keyword.