Sample solution

Content

#include <stddef.h>
#include <stdio.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");
}

double vector;

int main() {
double* x = vector;
printf("initialize x as one vector\n");
size_t maxlen = sizeof(vector)/sizeof(vector);
init_vector(x, maxlen, 1);
printf("x =      "); print_vector(x, maxlen, 1);

printf("using the space for two vectors\n");
size_t 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);
}

Remarks

Please note the trick that sizeof(vector)/sizeof(vector) delivers the dimension of vector as

• sizeof(vector) delivers the size of the entire array and as

• sizeof(vector) yields the element size.

But keep in mind that this trick works only for the original array but not for the pointers x or y.

Another interesting point is that in this example the local variables are declared as late as possible using an initializer whenever useful. This makes the code more readable (variables are declared close to the text where they are used) and initializers make sure that we work with well-defined values. Remember that local variables remain uninitialized otherwise.

The printing format for values of type double is “lf” (for long float), “le”, or “lg”. The last letter selects the prefered output format, i.e. “f” prefers a floating point notation, “e” switches to the exponential notation, and “g” choses the more readable variant in dependence of the actual value. The specification “4.1” tells that we want to output at least four characters, and that one place is reserved for the fractional part. There will be leading spaces if less space is required but the output is never shortened. Hence it is best practice to insert a space in front of the actual output which makes sure that subsequent floating point values in a line are separated.

Compilation and Execution

theon$gcc -Wall -o vector1 vector1.c theon$ ./vector1
initialize x as one vector
x =        1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0
using the space for two vectors
x =        1.0  2.0  3.0  4.0
y =        1.0  2.0  3.0  4.0
vector =   1.0  2.0  3.0  4.0  1.0  2.0  3.0  4.0
using the space for two interleaving vectors
x =        1.0  2.0  3.0  4.0
y =        1.0  2.0  3.0  4.0
vector =   1.0  1.0  2.0  2.0  3.0  3.0  4.0  4.0
theon\$