
Structures and Unions in C
Defining and Using Structures
Structures in C allow you to group variables of different types together under a single name. This is useful for organizing complex data.
struct Person {
char name[50];
int age;
float height;
};
struct Person person1;
strcpy(person1.name, "John Doe");
person1.age = 30;
person1.height = 5.9;
Accessing Structure Members
Members of a structure can be accessed using the dot (.) operator.
printf("Name: %s\n", person1.name); // Outputs: John Doe
printf("Age: %d\n", person1.age); // Outputs: 30
printf("Height: %.1f\n", person1.height); // Outputs: 5.9
Nested Structures
Structures can be nested within other structures to represent more complex data.
struct Address {
char street[50];
char city[50];
int zip;
};
struct Employee {
char name[50];
struct Address address;
float salary;
};
struct Employee emp;
strcpy(emp.name, "Alice Smith");
strcpy(emp.address.street, "123 Main St");
strcpy(emp.address.city, "Anytown");
emp.address.zip = 12345;
emp.salary = 75000.00;
typedef Keyword for Creating Custom Types
The typedef
keyword allows you to create new names for existing types, making code more readable and easier to manage.
typedef struct {
char make[20];
char model[20];
int year;
} Car;
Car myCar;
strcpy(myCar.make, "Toyota");
strcpy(myCar.model, "Corolla");
myCar.year = 2020;
Union vs. Structure
A union is similar to a structure, but its members share the same memory location. This means only one member can hold a value at any time.
Defining a Union
union Data {
int i;
float f;
char str[20];
};
union Data data;
data.i = 10;
printf("data.i: %d\n", data.i); // Outputs: 10
data.f = 220.5;
printf("data.f: %.1f\n", data.f); // Outputs: 220.5
strcpy(data.str, "C Programming");
printf("data.str: %s\n", data.str); // Outputs: C Programming
Note that updating one member of a union affects all other members due to shared memory.
Summary
In this post, we covered structures and unions in C, including how to define and use structures, access structure members, create nested structures, and use the typedef
keyword for custom types. We also discussed the key differences between unions and structures. Understanding these concepts is crucial for organizing complex data in C programming.
For further reading, consider these resources:
0 Comments: