So far, we've used arrays to store multiple values of the same data type.
But what if we want to store different types of information about the same object?
For example, a student may have:
Name →
charAge →
intMarks →
float
An array isn't ideal for this because all its elements must have the same type.
That's where structures come in.
What is a Structure?
A structure is a user-defined data type that allows us to group different types of data under a single name.
For example:
struct Student
{
char name[20];
int age;
float marks;
};
Here, Student contains three different types of data.
Creating a Structure Variable
After defining the structure, we can create a variable:
struct Student student1;
Now we can assign values to its members:
student1.age = 20;
student1.marks = 85.5;
For strings:
strcpy(student1.name, "John");
Accessing Structure Members
We use the dot (.) operator to access members.
printf("%d", student1.age);
printf("%f", student1.marks);
Example:
#include <stdio.h>
#include <string.h>
struct Student
{
char name[20];
int age;
float marks;
};
int main()
{
struct Student student1;
strcpy(student1.name, "John");
student1.age = 20;
student1.marks = 85.5;
printf("Name: %s\n", student1.name);
printf("Age: %d\n", student1.age);
printf("Marks: %.1f\n", student1.marks);
return 0;
}
Output:
Name: John
Age: 20
Marks: 85.5
Structure Initialization
We can also initialize a structure while declaring it:
struct Student student1 = {"John", 20, 85.5};
The values are assigned to the members in the same order in which they were defined.
Array of Structures
We can create an array of structures to store information about multiple students.
struct Student students[3];
Now each element can store one student's information.
For example:
students[0].age = 20;
students[1].age = 21;
students[2].age = 19;
This is very useful for storing records such as students, employees, products, or customers.
Structure with Pointers
Structures can also be accessed using pointers.
Suppose:
struct Student *ptr = &student1;
We can access its members using the arrow (->) operator:
printf("%d", ptr->age);
The -> operator is used when we have a pointer to a structure.
Structure vs Array
Structure | Array |
|---|---|
Can store different data types | Stores elements of the same type |
Members can have different names | Elements are accessed using indexes |
Uses | Uses |
Useful for representing records | Useful for storing collections of similar data |
In Simple Words
A structure allows us to group related data of different types under one name.
For example:
Student
├── name
├── age
└── marks
Structures are extremely useful for representing real-world entities such as students, employees, products, and customers.