A Structure is a user-defined data type in C that allows you to combine different data types under a single name. Unlike arrays, which store multiple elements of the same type, a structure can group variables of different types (int, float, char, etc.) that are logically related.
Example: To store information about a "Student," you might need an integer for Roll No, a string for Name, and a float for Marks. A structure allows you to group these into one entity.
The struct keyword is used to declare a structure. This creates a new data type template but does not allocate memory.
struct Student {
int rollNo;
char name[50];
float marks;
};
Once declared, you must define variables of that type to allocate memory.
struct Student s1, s2;
Structures can be initialized at the time of definition using curly braces.
struct Student s1 = {101, "Rahul", 85.5};To access individual members of a structure variable, we use the Dot Operator (.).
s1.rollNo = 102;
printf("Name: %s", s1.name);
Structures can be passed to functions just like standard variables. There are two main ways:
When using a pointer to a structure, we use the Arrow Operator (->) instead of the dot operator to access members.
struct Student *ptr;
ptr = &s1;
printf("Roll No: %d", ptr->rollNo); // Equivalent to (*ptr).rollNo
Used to store records for multiple entities of the same category.
struct Student classBCA[50]; // Stores info for 50 students
A structure can contain another structure as its member.
struct Date {
int day, month, year;
};
struct Student {
int rollNo;
struct Date dob; // Nested structure
};
These are structures that contain a pointer to a structure of the same type. They are the foundation of complex data structures like Linked Lists and Trees.
struct Node {
int data;
struct Node *next; // Points to the next node
};
A Union is similar to a structure, but all its members share the same memory location.
| Feature | Structure | Union |
|---|---|---|
| Memory | Allocates sum of all members' sizes. | Allocates size of the largest member. |
| Usage | All members can be used at once. | Only one member can hold a value at a time. |
int (4 bytes) and a char[10] (10 bytes), it takes 14 bytes. If it were a union, it would only take 10 bytes.-> when the left side is a pointer. Using . with a pointer is a common logic error.; at the end of the structure closing brace }. This is a syntax error.s1.dob.day.Q: Why use unions?
A: To save memory when you know that only one piece of data from a group will be needed at any given time.
Q: Can we compare two structure variables directly (s1 == s2)?
A: No. C does not allow direct comparison of structures. You must compare individual members one by one.