C Define & Use Structures – Create and Access Structured Data
In C programming, after defining a structure using the struct keyword, you can declare variables of that structure type and use them to group and manipulate data effectively.
🔹 Defining a Structure
Let’s define a simple structure for an employee:
struct Employee {
int id;
char name[50];
float salary;
};
🔹 Declaring Structure Variables
After defining the structure, you can declare variables like this:
// Declare one variable struct Employee emp1; // Declare multiple variables struct Employee emp2, emp3;
📝 Example: Initialize and Use Structure Members
Here’s a full example showing how to define, assign, and print structure members:
#include <stdio.h>
#include <string.h>
struct Employee {
int id;
char name[50];
float salary;
};
int main() {
struct Employee emp1;
emp1.id = 101;
strcpy(emp1.name, "John Doe");
emp1.salary = 55000.50;
printf("Employee ID: %d\n", emp1.id);
printf("Name: %s\n", emp1.name);
printf("Salary: %.2f\n", emp1.salary);
return 0;
}
📌 Note:
- Use the dot operator
.to access structure members. - Use
strcpy()to assign values to character arrays.
🎯 Practice Tip!
Try creating your own structure for a Product with fields like code, name, and price. Play with initializing and printing the data!