C Structures are a powerful feature in the C programming language that allow you to create complex data structures using basic C types. Unlike arrays, which are limited to a single type, structures can store values of different types, making them highly versatile in many use cases.
To define a structure, you use the struct
keyword followed by the name of the structure and a set of curly brackets {}. Inside the curly brackets, you can declare variables of different types that will make up the structure.
struct <structname> {
//...variables
};
For example, let’s create a structure called person
with an age
variable of type int and a name
variable of type char*.
struct person {
int age;
char* name;
};
Once you have defined a structure, you can declare variables of that structure type. You can declare a single variable or multiple variables at once.
struct person {
int age;
char* name;
} flavio;
// or
struct person {
int age;
char* name;
} flavio, people[20];
You can also declare variables separately from the structure definition.
struct person {
int age;
char* name;
};
struct person flavio;
To initialize a structure at declaration time, you can use the following syntax.
struct person {
int age;
char* name;
};
struct person flavio = {37, "Flavio"};
Once you have a structure variable, you can access its values using the dot (.) operator.
struct person {
int age;
char* name;
};
struct person flavio = {37, "Flavio"};
printf("%s, age %u", flavio.name, flavio.age);
You can also modify the values of a structure variable using the dot (.) operator.
struct person {
int age;
char* name;
};
struct person flavio = {37, "Flavio"};
flavio.age = 38;
Structures are extremely useful because you can pass them as function parameters or return values, allowing you to group variables together with labels. It’s important to note that structures are passed by copy unless you pass a pointer to a structure, in which case it is passed by reference.
To simplify working with structures, you can use the typedef
keyword. By using typedef
, you can create a new type name for your structure, making the code more readable.
For example, let’s create a typedef
for our person
structure.
typedef struct {
int age;
char* name;
} PERSON;
Now, you can declare new PERSON
variables without having to use the struct
keyword.
PERSON flavio;
You can also initialize PERSON
variables at declaration time.
PERSON flavio = {37, "Flavio"};
In conclusion, C Structures provide a convenient way to organize data of different types into a single structure. They give you the flexibility to work with complex data structures and make your code more efficient and readable.
Tags: C Structures, C Programming, Data Structures, Typedef