Structures are a fundamental feature in C programming, allowing you to define custom data structures to represent complex data. In this article, we will provide a comprehensive guide to defining structures in C, covering their syntax, usage, practical examples, and output.
What Are Structures?
A structure in C is a composite data type that groups together variables of different data types under a single name. It enables you to create custom data structures to represent real-world entities or complex data with multiple attributes.
Defining Structures
To define a structure in C, you use the struct
keyword, followed by a name for the structure, and a list of member variables enclosed in curly braces {}
.
#include <stdio.h>
// Define a structure named 'Person'
struct Person {
char name[50];
int age;
float height;
};
In this example, we define a structure named Person
with three member variables: name
, age
, and height
.
Declaring Structure Variables
After defining a structure, you can declare variables of that structure type.
struct Person person1; // Declare a 'Person' variable named 'person1'
Accessing Structure Members
You can access the members of a structure variable using the dot .
operator.
#include <stdio.h>
struct Person {
char name[50];
int age;
float height;
};
int main() {
struct Person person1;
strcpy(person1.name, "Alice");
person1.age = 25;
person1.height = 165.5;
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.1f\n", person1.height);
return 0;
}
The output will be:
Name: Alice
Age: 25
Height: 165.5
Initializing Structure Variables
You can initialize structure variables at the time of declaration.
struct Person person1 = {"Bob", 30, 180.0};
Nested Structures
Structures can be nested within other structures to create more complex data structures.
#include <stdio.h>
struct Address {
char street[50];
char city[30];
char state[20];
char zip[10];
};
struct Person {
char name[50];
int age;
struct Address address;
};
int main() {
struct Person person1 = {"John", 35, {"123 Main St", "Springfield", "IL", "62701"}};
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Address: %s, %s, %s %s\n", person1.address.street, person1.address.city, person1.address.state, person1.address.zip);
return 0;
}
The output will be:
Name: John
Age: 35
Address: 123 Main St, Springfield, IL 62701