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:

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

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 C1andC2` 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 ...

Check Bravo! You just have to use the = operator, but you can also assign the fields one by one. Try again...

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

Check Bravo! The == operator does not work on structures, you have to compare the fields individually. However, in this case, a minimum of 16 bytes is required. Try again...

What is the size of the structure below?

// Structure circle
struct circle {
  int cx,cy;      // Center
  double radius;  // Radius
};
Check Bravo! The size of a structure is not necessarily equal to the sum of the size of its fields. Try again...

See also


Last update : 12/01/2022