/* Include the system headers we need */ #include<stdlib.h> #include<stdio.h>
/* Include our header */ #include"vector.h"
/* Define what our struct is */ structvector_t { size_t size; int *data; };
/* Utility function to handle allocation failures. In this case we print a message and exit. */ staticvoidallocation_failed(){ fprintf(stderr, "Out of memory.\n"); exit(1); }
voidvector_set(vector_t *v, size_t loc, int value){ if (loc < v->size) { v->data[loc] = value; } else { int *new_data = (int *)malloc((loc + 1) * sizeof(int)); if (new_data == NULL) { allocation_failed(); } for (int i = 0; i <= loc; i ++) new_data[i] = 0; new_data[loc] = value; for (int i = 0; i < v->size; i ++) { new_data[i] = v -> data[i]; } free(v->data); v -> data = new_data; v->size = loc + 1; } }