Welcome to our deep dive into C Structures! Structures are a fundamental data type in C programming that allow you to group variables of different types together. Let's explore how to access these structured data efficiently.
A structure is a user-defined data type that bundles together various types of variables under a single identifier.
struct student {
char name[50];
int age;
float gpa;
};In the above example, we have created a structure named student that contains three variables: name (char array), age (integer), and gpa (floating-point number).
To access individual members of a structure, you need to use the . operator.
struct student s1;
strcpy(s1.name, "John Doe");
s1.age = 20;
s1.gpa = 3.8;In the above example, we have created a student structure variable named s1, and then initialized its members: name, age, and gpa.
Let's create a simple program that stores information about employees and calculates their salaries.
#include <stdio.h>
#include <string.h>
struct employee {
char name[50];
int age;
float salary;
};
int main() {
struct employee emp[3];
int i;
for(i = 0; i < 3; i++) {
printf("Enter name, age, and salary for employee %d:\n", i + 1);
scanf("%s %d %f", emp[i].name, &emp[i].age, &emp[i].salary);
}
printf("\nEmployee Details:\n");
for(i = 0; i < 3; i++) {
printf("\nEmployee %d\n", i + 1);
printf("Name: %s\n", emp[i].name);
printf("Age: %d\n", emp[i].age);
printf("Salary: %.2f\n", emp[i].salary);
}
return 0;
}In this example, we have created a structure named employee that stores name, age, and salary. The main() function initializes an array of employee structures, reads input from users for each structure, and then displays the data.
Structures can also be accessed using pointers for more flexibility.
struct employee *ptr = &emp[0]; // Pointer pointing to the first employee structure
ptr->age = 25; // Changing the age of the first employeeUsing pointers allows you to perform operations on structures dynamically, such as allocating memory for structures at runtime.
You can also create arrays of structures, as we did in our practical example. This allows you to store multiple instances of a structure for different data.
What is the purpose of a structure in C programming?
That's it for our C Structure Access lesson! With this knowledge, you'll be able to work with structured data efficiently. Happy coding! 🤖💻🚀