Consider an implementation of n-dimensional vectors using the structure
typedef struct {int size; double* data;} nvector;
Implement a set of functions to deal with these vectors.
The declarations must be kept in the header file nvector.h,
#ifndef HAVE_NVECTOR_H /* for multiple includes */
typedef struct {int size; double* data;} nvector;
nvector* nvector_alloc (int n); /* allocates memory for size-n vector */
void nvector_free (nvector* v); /* frees memory */
void nvector_set (nvector* v, int i, double value); /* v_i ← value */;
double nvector_get (nvector* v, int i); /* returns v_i */
double nvector_dot_product (nvector* u, nvector* v); /* returns dot-product */
/* optional */
void nvector_print (char* s, nvector* v); /* prints s and then vector */
void nvector_set_zero (nvector* v); /* all elements ← 0 */
int nvector_equal (nvector* a, nvector* b); /* 1, if equal, 0 otherwise */
void nvector_add (nvector* a, nvector* b); /* a_i ← a_i + b_i */
void nvector_sub (nvector* a, nvector* b); /* a_i ← a_i - b_i */
void nvector_scale (nvector* a, double x); /* a_i ← x*a_i */
/* */
#define HAVE_NVECTOR_H
#endif
The implementations of the functions must be in the file
nvector.c. You should #include"nvector.h"
in nvector.c to allow the compiler to check the declarations.
Like this,
#include<stdio.h>
#include"nvector.h"
nvector* nvector_alloc(int n){
nvector* v = malloc(sizeof(nvector));
(*v).size = n;
(*v).data = malloc(n*sizeof(double));
if( v==NULL ) fprintf(stderr,"error in nvector_alloc\n");
return v;
}
void nvector_free(nvector* v){ free(v->data); free(v);}
void nvector_set(nvector* v, int i, double value){ (*v).data[i]=value; }
double nvector_get(nvector* v, int i){return (*v).data[i]; }
/* ... */
#include "nvector.h"
#include "stdio.h"
#include "stdlib.h"
#define RND (double)rand()/RAND_MAX
int main()
{
int n = 5;
printf("\nmain: testing nvector_alloc ...\n");
nvector *v = nvector_alloc(n);
if (v == NULL) printf("test failed\n");
else printf("test passed\n");
printf("\nmain: testing nvector_set and nvector_get ...\n");
double value = RND;
int i = n / 2;
nvector_set(v, i, value);
double vi = nvector_get(v, i);
if (double_equal(vi, value)) printf("test passed\n");
else printf("test failed\n");
printf("\nmain: testing nvector_add ...\n");
nvector *a = nvector_alloc(n);
nvector *b = nvector_alloc(n);
nvector *c = nvector_alloc(n);
for (int i = 0; i < n; i++) {
double x = RND, y = RND;
nvector_set(a, i, x);
nvector_set(b, i, y);
nvector_set(c, i, x + y);
}
nvector_add(a, b);
nvector_print("a+b should = ", c);
nvector_print("a+b actually = ", a);
if (nvector_equal(c, a)) printf("test passed\n");
else printf("test failed\n");
nvector_free(v);
nvector_free(a);
nvector_free(b);
nvector_free(c);
return 0;
}
Implement range checking using <assert.h>, for example,
void nvector_set(nvector* v, int i, double value){
assert( 0 <= i && i < (*v).size )
(*v).data[i]=value;
}