Lesson 12.4. Structures and functions

Structures, as well as variables, can be passed as parameters in functions:

Call by value

When a structure is called by value in a function, its content is copied locally into the function, as for variables.

// Call by value
void fct (struct vector v);

If a function has to modify the content of a structure, a call by reference must be used.

Call by reference

As for variables, passing a structure pointer as a parameter to a function allows it to access its contents in read and write mode.

// Call by reference
void fct (struct vector * v);

Note that in the case of a structure pointer, the fields are accessible with the -> operator:

// x field of the structure pointer v
v->x

Exercises

Exercise 1

Create a vector structure that contains the coordinates of a vector in 3 dimensions. Write a function norm() that receives a vector as a parameter and returns the norm (length) of the vector.

Here is an example of how to calculate the norm:

x=2.3
y=3.4
z=4.5
The norm of the vector is : 6.090977
#include <stdio.h>
#include <math.h>

// Vector structure
struct vector {
    double x, y, z;
};

// Return the norm of vector v
double norm(struct vector v);

int main(void) {

    // Create a vector
    struct vector vec;

    // Ask the vector to the user
    printf ("x=");
    scanf("%lf", &vec.x);
    printf ("y=");
    scanf("%lf", &vec.y);
    printf ("z=");
    scanf("%lf", &vec.z);

    // Display the norm of the vector
    printf ("The norm of the vector is: %lf\n", norm(vec));

    return 0;
}

// Return the norm of vector v
double norm(struct vector v) {
    return sqrt(v.x*v.x + v.y*v.y + v.z*v.z);
}

Exercise 2

Create a RGB structure that contains three colors (red, green and blue) and a grey value. Write a grayscale() function that computes and updates the grey field of the structure by averaging the three colors.

$$ grey = \dfrac{red+green+blue}{3} $$

Here is an example:

R = 120
G = 180
B = 64
---------------
Grey = 121
#include <stdio.h>

// Declare the RGB structure
struct RGB {
    int red, green, blue;
    int grey;
};

// Calculate the average grey
void grayscale(struct RGB *C);

int main(void) {
    // Create a color
    struct RGB color = {120 , 180 , 64 };

    // Call the grayscale function to calculate the grey value
    grayscale(&color);

    // Display colors and grey value
    printf ("R = %d\n", color.red);
    printf ("G = %d\n", color.green);
    printf ("B = %d\n", color.blue);
    printf ("---------------\n");
    printf ("Grey = %d\n", color.grey);
    return 0;
}

// Calculate the average grey
void grayscale(struct RGB *C) {
    C->grey = (C->red + C->green + C->blue) / 3;
}

Quiz

Why is there no real question in this quiz?

Check Bravo! Will anyone, one day, really read this line... Try again...

See also


Last update : 11/30/2026