Lesson 12.3. Structures and pointers

Structure pointers

Structure pointers use the same syntax as variables:

struct vector v;
struct vector * address = &v;

The pointer contains the address of the first field of the structure. When we increment a structure pointer, the pointer increase by the size of the structure (which is not necessarily equal to the sum of the field sizes).

Field access

The access to the fields of the structure can be done with the classical syntax of pointers respecting the priority of the operators :

(*ptr).field

But there is a more user-friendly syntax that uses the -> operator:

ptr->field

This syntax is to be preferred, but can only be used with a structure pointer.

Note: this syntax is important because it is widely used in C++ for class pointers. A class in C++ is an extension of the structures in C that contains functions in addition to fields.

Example

The following code creates a structure pointer and assigns a value to each field using the two syntaxes presented above:

// Declare a vector and a vector pointer
struct vector vec;
struct vector * ptr = &vec;

// Standard pointers
(*ptr).x = 1.2;
// Structure pointer (recommended)
ptr->y = 2.4;

Exercises

Exercise 1

Write the code for the function homothety() which performs a homothety of vector passed by reference (pointer). The second parameter of the function is the homothety factor. As a reminder, the homothety of a vector \( \vec{v} \) with factor \(h\) is given by :

$$ \vec{V} = h \times \vec{v} $$

Here is the expected output:

before: x=1.2 y=3.4
After : x=2.4 y=6.8

Exercise 2

The following code is provided which retrieves the current local time from the timeinfo structure (type struct tm). Referring to the documenation of the tm structure, complete the program so that it displays the time.

// Source : http://www.cplusplus.com/reference/ctime/localtime/
// Get local time from timeinfo
time_t rawtime;
struct tm * timeinfo;

time (&rawtime);
timeinfo = localtime (&rawtime);

Here is a possible display:

15:49 29s

Quiz

A structure pointer points to ...

Check Bravo! The pointer of a structure points to the address of the first field. Try again...

Which syntaxes allow to access the field of a structure pointer?

struct article * ptr;
Check Bravo! It is indeed necessary to pay attention to the operators' priority. Try again...

Which syntaxes allow to access the field of a structure pointer?

struct article * ptr;
Check Bravo! This syntax should be preferred. Try again...

When incrementing a structure pointer ...

Check Bravo! Remember that the size of the structure is not necessarily the sum of the size of its fields. Try again...

See also


Last update : 12/03/2022