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
32
33
34
35
36
37
38
39
40
41
#include <stdlib.h>
#include <stdio.h>

struct Vector
{
    double * const data;
    const size_t dim;
};

int
main(void)
{
    struct Vector x = {
        malloc(4 * sizeof(x.data)),     // allocate memory for 4 double
        4,                              // dim is hard coded to 4
    };

    // check if memory could be allocated
    if (!x.data) {
        fprintf(stderr, "allocating memoy for vector with %zu elemets failed\n",
                x.dim);
        exit(1);
    }
    
    // init vector elements
    for (size_t i = 0; i < x.dim; ++i) {
        x.data[i] = 42 + i;
    };

    // print vector elements
    for (size_t i = 0; i < x.dim; ++i) {
        printf("%lf", x.data[i]);
        if (i + 1 < x.dim) {
            printf(", ");
        }
    };
    printf("\n");

    // release memory
    free(x.data);
}