#include #include #include #include #define SIZE 20 typedef struct sensor_reading { long ts; int temp; } Reading; // -------------------------------------------------- // Initialize array with some random values void init(Reading array_samples[], int nb_samples, int delta_time) { int i; int time = 0; for (i = 0 ; i < nb_samples; i++) { Reading r; r.ts = time; time += delta_time; if ( (i % 2) ) { r.temp = 68; } else { r.temp = 67; } // Important. The following statement makes copy of whole structure! array_samples[i] = r; } } // -------------------------------------------------- // Just prints the content of the array void print(Reading array_samples[], int nb_samples) { int i; printf("["); for (i = 0 ; i < nb_samples; i++) { printf("(%ld,%d)", array_samples[i].ts, array_samples[i].temp); } printf("]\n"); } // -------------------------------------------------- // Arguments should be: nb samples and delta time int main(int argc, char** argv) { if ( argc <= 2 ) { fprintf(stderr,"Usage: %s nb_samples delta_time\n", argv[0]); return 1; } int nb_samples = atoi(argv[1]); int delta_time = atoi(argv[2]); Reading *array_samples = (Reading *)malloc( nb_samples * sizeof(Reading)); init(array_samples,nb_samples,delta_time); print(array_samples,nb_samples); int capacity = nb_samples; while ( true ) { // Read next sample Reading r; printf("Enter next sample: "); scanf(" %ld %d",&(r.ts),&(r.temp)); // If out-of-space, double the capacity if ( nb_samples >= capacity ) { printf("\nOut of space, doubling the size...\n"); capacity = 2*capacity; Reading *old = array_samples; // Allocate a bigger array array_samples = (Reading *)malloc( capacity * sizeof(Reading)); if ( ! array_samples ) { fprintf(stderr,"Out of memory\n"); return 1; } // Copy old array into new location // memcpy is general utility to copy chunks of memory memcpy(array_samples,old,(nb_samples*sizeof(Reading))); // Deallocate old array free(old); // Note that we could do all this in one step by using realloc } array_samples[nb_samples] = r; nb_samples++; print(array_samples,nb_samples); } return 0; }