/

C Structures: An Introduction

C Structures: An Introduction

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.

1
2
3
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*.

1
2
3
4
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.

1
2
3
4
5
6
7
8
9
10
11
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.

1
2
3
4
5
6
struct person {
int age;
char* name;
};

struct person flavio;

To initialize a structure at declaration time, you can use the following syntax.

1
2
3
4
5
6
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.

1
2
3
4
5
6
7
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.

1
2
3
4
5
6
7
8
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.

1
2
3
4
typedef struct {
int age;
char* name;
} PERSON;

Now, you can declare new PERSON variables without having to use the struct keyword.

1
PERSON flavio;

You can also initialize PERSON variables at declaration time.

1
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