C structure

Introduction to C structure

usestructKeywords We can use basic C types to create complex data structures.

A structure is a collection of different types of values.ArrayThe C language in the C language is limited to one type, so in many use cases, the structure can prove to be very interesting.

This is the syntax of the structure:

struct <structname> {
  //...variables
};

example:

struct person {
  int age;
  char *name;
};

You can declare a variable with this structure type by adding the variable after the braces and before the semicolon, as shown below:

struct person {
  int age;
  char *name;
} flavio;

Or more, as follows:

struct person {
  int age;
  char *name;
} flavio, people[20];

In this case, I declare apersonVariable nameflavio, And 20 arrayspersonnamepeople.

We can also declare variables later using the following syntax:

struct person {
  int age;
  char *name;
};

struct person flavio;

We can initialize a structure at the time of declaration:

struct person {
  int age;
  char *name;
};

struct person flavio = { 37, “Flavio” };

Once the structure is defined, you can use dots to access the values in it:

struct person {
  int age;
  char *name;
};

struct person flavio = { 37, “Flavio” }; printf("%s, age %u", flavio.name, flavio.age);

We can also change the value using dot syntax:

struct person {
  int age;
  char *name;
};

struct person flavio = { 37, “Flavio” };

flavio.age = 38;

Structures are very useful because we can pass them as function parameters or return values, embed various variables in them, and each variable has a label.

It is important to note that the structure isPass by copyUnless of course you passpointerTo a structure, in which case it is passed by reference.

usetypedefWe can simplify the code when dealing with structures.

Let's take an example:

typedef struct {
  int age;
  char *name;
} PERSON;

We use the created structuretypedefBy convention, it is usually uppercase.

Now we can declare the newPERSONVariables like this:

PERSON flavio;

We can initialize them at declaration time in the following ways:

PERSON flavio = { 37, "Flavio" };

Download mine for freeC manual


More clang tutorials: