Structures in C: An Introduction
In this tutorial, we will introduce Structures in C, a significant feature that brings together different data types under one roof, helping to make the programming language powerful and flexible. Structures are an integral part of C, and it's essential to grasp this topic to progress in your C programming journey.
Let's get started!
What is a Structure?
A structure is a collection of variables under a single name. These variables can be of different types, and each one is called a member or a field of the structure. The members of a structure are stored in contiguous memory locations, which means that they all share the same memory address.
Defining a Structure
To define a structure, you use the struct
keyword, followed by your defined structure name and the variables inside curly brackets {}
. Here is the syntax:
struct structureName {
dataType member1;
dataType member2;
...
};
For example, let's define a structure named Student
:
struct Student {
char name[50];
int roll;
float marks;
};
In the Student
structure, name
, roll
, and marks
are members of the structure.
Declaring Structure Variables
We can declare structure variables in two different ways:
- When the structure is defined:
struct Student {
char name[50];
int roll;
float marks;
} s1, s2;
In this case, s1
and s2
are variables of the structure type Student
.
- After the structure is defined:
struct Student {
char name[50];
int roll;
float marks;
};
struct Student s1, s2;
Accessing Structure Members
To access the members of a structure, we use a dot .
operator, also known as the structure member operator. Here is the syntax:
structureVariable.member
For example, if we want to access the roll
member of the Student
structure for s1
, we write s1.roll
.
Initializing a Structure
We can initialize a structure at the time of declaration:
struct Student {
char name[50];
int roll;
float marks;
} s1 = {"John", 23, 85.5};
In this case, John
, 23
, and 85.5
are initial values of name
, roll
, and marks
for s1
, respectively.
Structures within Structures (Nested Structures)
We can also have structures within structures, known as nested structures. For example:
struct Address {
char city[50];
int pin;
};
struct Employee {
char name[50];
struct Address addr;
};
In the above example, Employee
has two members: name
and addr
. The addr
itself is a structure having two members: city
and pin
.
Understanding structures can take some time, but with consistent practice, you will get the hang of it. The structure is a powerful tool in C that allows more complex data models to be created, opening up a world of possibilities for more advanced programming. Keep practicing, and happy coding!
In the next tutorial, we'll look at Unions in C, which are similar to structures with a few key differences. Stay tuned!