C Structure Access 🎯

beginner
10 min

C Structure Access 🎯

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.

Understanding C Structures 📝

A structure is a user-defined data type that bundles together various types of variables under a single identifier.

c
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).

Accessing Structure Members 💡

To access individual members of a structure, you need to use the . operator.

c
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.

Practical Example 👨‍💻

Let's create a simple program that stores information about employees and calculates their salaries.

c
#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 and Pointers 📝

Structures can also be accessed using pointers for more flexibility.

c
struct employee *ptr = &emp[0]; // Pointer pointing to the first employee structure ptr->age = 25; // Changing the age of the first employee

Using pointers allows you to perform operations on structures dynamically, such as allocating memory for structures at runtime.

Structures and Arrays 💡

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.

Quiz 📝

Quick Quiz
Question 1 of 1

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! 🤖💻🚀