/* * Contrived example of dynamically-allocated 1D array. * Also uses strtol to parse command-line arguments. * * Program takes two command-line arguments, seed and size, and uses * them to generate array of 1D "random" doubles in the range [0 .. 1], * for which it then computes variance. */ #include #include double square(double d); double variance(long size, double vals[]); int main(int argc, char *argv[]) { if (argc < 3) { printf("usage %s seed size\n", argv[0]); return EXIT_FAILURE; } char *endptr; int seed = strtol(argv[1], &endptr, 10); if (*endptr != '\0') { printf("usage %s seed size\n", argv[0]); return EXIT_FAILURE; } long size = strtol(argv[2], &endptr, 10); if (*endptr != '\0') { printf("usage %s seed size\n", argv[0]); return EXIT_FAILURE; } double *vals = malloc(sizeof(*vals) * size); if (vals == NULL) { printf("could not allocate space for %ld values\n", size); return EXIT_FAILURE; } srand(seed); for (long i = 0; i < size; ++i) { vals[i] = ((double) rand()) / RAND_MAX; } double vals_variance = variance(size, vals); printf("variance is %g\n", vals_variance); free(vals); return EXIT_SUCCESS; } double square(double d) { return d*d; } double variance(long size, double vals[]) { double sum = 0.0; for (long i = 0; i < size; i++) { sum += vals[i]; } double average = sum/size; double variance_sum = 0.0; for (long i = 0; i < size; i++) { variance_sum += square(vals[i]-average); } return variance_sum/size; }