# Sample solution

#### Content

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

void init_vector(double* v, size_t len, ptrdiff_t incr) {
for (size_t i = 0; i < len; ++i) {
v[i*incr] = i + 1;
}
}

void print_vector(double* v, size_t len, ptrdiff_t incr) {
for (size_t i = 0; i < len; ++i) {
printf(" %4.1lf", v[i*incr]);
}
printf("\n");
}

int main() {
size_t maxlen;
printf("size of the array: ");
if (scanf("%zu", &maxlen) != 1) return 1;
double* vector = malloc(sizeof(double)*maxlen);
if (!vector) {
printf("out of memory\n"); return 1;
}

double* x = vector;
printf("initialize x as one vector\n");
size_t len = maxlen;
init_vector(x, len, 1);
printf("x =      "); print_vector(x, len, 1);

printf("using the space for two vectors\n");
len = maxlen/2;
double* y = vector + len;
init_vector(x, len, 1); init_vector(y, len, 1);
printf("x =      "); print_vector(x, len, 1);
printf("y =      "); print_vector(y, len, 1);
printf("vector = "); print_vector(vector, maxlen, 1);

printf("using the space for two interleaving vectors\n");
y = vector + 1;
init_vector(x, len, 2); init_vector(y, len, 2);
printf("x =      "); print_vector(x, len, 2);
printf("y =      "); print_vector(y, len, 2);
printf("vector = "); print_vector(vector, maxlen, 1);

free(vector);
}


## Compilation and execution

theon$gcc -Wall -o example2_vector example2_vector.c theon$ echo 16 | ./example2_vector
size of the array: initialize x as one vector
x =        1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  9.0 10.0 11.0 12.0 13.0 14.0 15.0 16.0
using the space for two vectors
x =        1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0
y =        1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0
vector =   1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0
using the space for two interleaving vectors
x =        1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0
y =        1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0
vector =   1.0  1.0  2.0  2.0  3.0  3.0  4.0  4.0  5.0  5.0  6.0  6.0  7.0  7.0  8.0  8.0
theon\$