UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

5.7.2.  Structures as parameters

When a function is called in C, the values of the parameters are copied from the invoking scope (place with the function call) to the invoked scope (body of the function). The following program shows the execution of a function that receives two structures as parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <stdio.h>
#include <math.h>
/* Structure definition */
struct coordinates 
{
    float x;
    float y;
    float z;
};
/* Definition of the function to calculate distance between two points */
float distance(struct coordinates a, struct coordinates b) 
{
    return sqrtf(pow(a.x - b.x, 2.0) + 
                 pow(a.y - b.y, 2.0) + 
                 pow(a.z - b.z, 2.0));
}

int main() 
{
    /* Declaration and initialization of two variables */
    struct coordinates point_a = { 3.5e-120, 2.5, 1.5 };
    struct coordinates point_b = { 5.3e-120, 3.1, 6.3 };
    float d; /* Store the result */

    /* Call function with the two structures */    
    d = distance(point_a, point_b);
    /* Print the result */
    printf("%f\n", d);

    return 0;
}

In line 26 a copy of the structures point_a and point_b from the scope of the main is performed over the structures a and b in the scope of the distance function. This copy has two effects: the program requires as much time as data are in the structure, and during the execution of the function, two complete copies of the structures are maintained. The use of pointers offers a more efficient alternative. The function can be re-written to receive two pointers to structures. The definition of the function is now:

float distance(struct coordinates *a_ptr, struct coordinates *b_ptr) 
{
    return sqrtf(pow(a_ptr->x - b_ptr->x, 2.0) + 
                 pow(a_ptr->y - b_ptr->y, 2.0) + 
                 pow(a_ptr->z - b_ptr->z, 2.0));
}

The function call in line 26 is now:

d = distance(&point_a, &point_b);

With this new version, the program executes exactly the same calculations, obtains the same result, but its execution is faster and uses less memory.

Suggestion

The program in the previous example uses the library functions pow and sqrtf. In a window with the command interpreter use the man command followed by each of these names to find out what they do. To use these functions the file math.h must be included using the directive in line 2. Furthermore, the library of mathematical functions must be explicitly included when compiling with the option -lm in the command

gcc -Wall -o program file.c -lm

in which you replace file.c with the name of your file.

Modify the program in the example to increase the precision of the calculations. Compare both results.