In C programming, a struct (or structure) is a collection of variables (can be of different types) under a single name.
Syntax
Example:
Create struct Variable
When a struct type is declared, no storage or memory is allocated. To allocate memory of a given structure type and work with it, we need to create variables.
Here’s how we create structure variables:
Another way of creating a struct variable is:
In both cases:
person1 and person2 are struct Person variables
p[] is a struct Person array of size 20.
Access Members of a Structure
There are two types of operators used for accessing members of a structure.
Suppose, you want to access the salary of person2. Here’s how you can do it:
Example C structs:
Output:
Keyword typedef
We use the C typedef Function keyword to create an alias name for data types. It is commonly used with structures to simplify the syntax of declaring variables.
Example:
We can use typedef to write an equivalent code with a simplified syntax:
Example: C typedef
Output:
Nested Structures
You can create structures within a structure in C programming.
Example:
Suppose, you want to set imag of num2 variable to 11. Here’s how you can do it: