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:
struct employee{
int code; => this declares a new user-defined datatype
float salary;
char name[10];
}; • semicolon is important
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.
struct employee facebook[100]; =>an array of structures
We can access the data using:
facebook[0].code=100;
facebook[1].code=101;
..........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 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.
No comments:
Post a Comment