Structures in C - Basics and Usage


Introduction

Structures are a fundamental concept in C programming, allowing you to define custom data types that can hold multiple variables of different data types under a single name. They are especially useful when you need to group related data together. In this guide, we'll explore the basics of structures in C and provide you with sample code to demonstrate their usage.


What is a Structure?

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 a custom data structure that can represent more complex data entities, such as a person's information or the properties of a point in a 2D space.


Declaring and Defining Structures

Here's how you declare and define a structure in C:

#include <stdio.h>
// Define a structure named 'Person'
struct Person {
char name[50];
int age;
};
int main() {
// Declare a structure variable of type 'Person'
struct Person person1;
// Initialize the structure members
strcpy(person1.name, "John");
person1.age = 30;
// Access and print structure members
printf("Name: %s\\n", person1.name);
printf("Age: %d\\n", person1.age);
return 0;
}

In this example, we define a structure named

Person
with two members:
name
(a character array) and
age
(an integer). We then declare a structure variable
person1
of type
Person
and initialize its members.


Accessing Structure Members

You can access structure members using the dot operator (

.
):

#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
struct Point p1;
p1.x = 10;
p1.y = 20;
printf("Coordinates: (%d, %d)\\n", p1.x, p1.y);
return 0;
}

In this example, we define a structure

Point
with two members:
x
and
y
. We declare a structure variable
p1
and access its members to print the coordinates.


Structures and Functions

Structures are often used in functions to pass and manipulate complex data:

#include <stdio.h>
struct Rectangle {
int width;
int height;
};
// Function to calculate the area of a rectangle
int calculateArea(struct Rectangle r) {
return r.width * r.height;
}
int main() {
struct Rectangle myRect;
myRect.width = 5;
myRect.height = 10;
int area = calculateArea(myRect);
printf("Area of the rectangle: %d\\n", area);
return 0;
}

In this example, we define a structure

Rectangle
and a function
calculateArea
that takes a
Rectangle
structure as a parameter to calculate the area. We create a
myRect
structure and pass it to the function.


Conclusion

Structures are a versatile feature of C programming, allowing you to create custom data types that can represent complex data entities. This guide has introduced you to the basics of structures, including declaration, definition, member access, and their use in functions. As you continue your journey in C programming, you'll discover the power of structures in handling more intricate data structures.