Structures in C
What is a Structure?
A structure in C is a user-defined data type that allows grouping of variables of different data types under a single name. Structures are used to represent a record, where each field can hold data of different types, such as integers, floats, and characters. This is particularly useful for managing complex data sets in a more organized way.
Structures are defined using the struct
keyword. Each structure contains members or fields, which represent the individual variables grouped within the structure.
Structure Type Declarations
The first step in using structures is declaring a structure type. This is done using the struct
keyword, followed by the structure name and the definition of its members within curly braces.
Syntax
The general syntax for declaring a structure type is:
struct StructureName {
data_type member1;
data_type member2;
...
};
Here’s an example structure type declaration to represent a student:
struct Student {
int roll_no;
char name[50];
float marks;
};
In this example, the Student
structure type has three members: roll_no
(integer), name
(character array), and marks
(float).
Structure Declarations
After defining a structure type, you can declare variables of that structure type. Declaring a structure variable is similar to declaring variables of other data types, but with the struct
keyword.
The syntax for declaring a structure variable is:
struct StructureName variable_name;
Here’s how to declare a Student
variable:
struct Student student1;
Example: Declaring and Accessing Structure Members
After declaring a structure variable, you can access its members using the .
operator. In the example below, we create a Student
structure variable and assign values to each member.
Example:
#include <stdio.h>
// Defining a structure type Student
struct Student {
int roll_no;
char name[50];
float marks;
};
// Main Function
int main() {
// Declaring a structure variable
struct Student student1;
// Assigning values to structure members
student1.roll_no = 101;
snprintf(student1.name, 50, "Alice");
student1.marks = 85.5;
// Accessing and displaying structure members
printf("Student Roll No: %d\n", student1.roll_no);
printf("Student Name: %s\n", student1.name);
printf("Student Marks: %.2f\n", student1.marks);
return 0;
}
Output
Student Name: Alice
Student Marks: 85.50
Advantages of Using Structures
Structures provide several advantages:
- Organization: Structures group related data into a single entity, making code more organized and easier to understand.
- Data Management: Structures are particularly useful for managing complex data sets, such as student records, employee details, or inventory data.
- Efficient Memory Usage: Structures use memory efficiently by allowing different data types to be stored together, minimizing data redundancy.