# Lesson 12.2. Properties of structures in C

## Assignment of structures

It is possible to assign a structure as a whole:

``structure_A = structure_B ;``

The above code copies all fields from `structure_B` into `structure_A`.

## Comparison of structures

It is not possible to compare two structures with the `==` operator.

``````// DOES NOT COMPARE STRUCTURES
if (structure_A == structure_B)...``````

To test if two structures are identical, each field must be tested individually.

## Scope of structures

The scope of the structures is similar to the variables:

• local : within a function, it is only accessible from this function.
• global : outside a function, it is accessible to all the part of the code that follows its declaration.

## Size of a structure

It is possible to know the size of a structure in memory with the `sizeof()` function. Be careful, the size of a structure is not always equal to the sum of the size of its fields. Without going into details, memory alignment allows to increase the execution speed.

## Exercises

### Exercise 1

Create a `vector` structure that contains 3 double precision fields `x`, `y` and `z`. Create a variable `v` of type `vector` and display the size

• of the structure `vector` ;
• of the variable `v` ;
• of each field of the structure.

Here is the expected output:

```Size of structure vector : 24 bytes
Size of variable v : 24 bytes
Size of v.x : 8 bytes
Size of v.y : 8 bytes
Size of v.z : 8 bytes
```

### Exercise 2

The following `circle` structure is provided:

``````struct circle {
int cx,cy;      // Center
double radius;  // Radius
};``````

Declare a variable `C1` for a circle centered in (2,4) and with a radius of 2.5. Copy the circle into a new variable `C2` previously declared.

Check that the copy has been done correctly (C1 equals C2) and that the variables C1`and`C2` have two distinct addresses:

```Circle C1 with radius 2.50 and center (2,4)
Circle C2 with radius 2.50 and center (2,4)
The structures are identical
Address of C1 : 0x7fff25306248
Address of C2 : 0x7fff25306238
```

## Quiz

To copy a variable of type structure in another ...

To check that variables of type structure are identical ...

What is the size of the structure below?

``````// Structure circle
struct circle {
int cx,cy;      // Center
double radius;  // Radius
};``````

## See also

Last update : 12/01/2022