UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

Another scenario where pointers are very useful is to link data structures. Let us assume that in the agenda of your mobile phone you may store for each contact a map. One possible data structure to store the data for each contact would have a field to store this map. It follows on possibility to define these data structures.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#define SIZE 64
struct map_data 
{
/* Data related to the map */
...
};

struct contact_data 
{
    char firstname[SIZE];
    char lastname[SIZE];
    ...
    /* Map data for this contact */
    struct map_data map;
};

If the agenda stores 100 contacts, each one of them has space to store the map data. But imagine that this map occupies a lot of memory due to the graphics, and several users have the same map so that large portions of memory are simply duplicates. Ideally we would like to maintain the possibility of storing one map per contact, but at the same time avoid duplicates. One possible solution is to store separately the set of users and the set of maps. In the structure with the user data a link to the appropriate map is inserted. With this solution, if several users share the same map, all of them will be linked to a single copy. This link can be implemented using pointers as it is shown in the following definitions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#define SIZE 64
struct map_data 
{
/* Data related to the map */
...
};

struct contact_data 
{
    char firstname[SIZE];
    char lastname[SIZE];
    ...
    /* Link to the map data*/
    struct map_data *map;
};

The following figure shows the difference in memory size using the two solutions for the case of five contacts sharing two maps.

With the new solution, the access to the map data must be done with the indirection operator -> because the field with the data map is a pointer.