1
0

dyn_arr.c 995 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /* dyn_arr.c -- dynamically allocated array */
  2. #include <stdio.h>
  3. #include <stdlib.h> /* for malloc(), free() */
  4. int main(void)
  5. {
  6. double * ptd;
  7. int max;
  8. int number;
  9. int i = 0;
  10. puts("What is the maximum number of type double entries?");
  11. if (scanf("%d", &max) != 1)
  12. {
  13. puts("Number not correctly entered -- bye.");
  14. exit(EXIT_FAILURE);
  15. }
  16. ptd = (double *) malloc(max * sizeof (double));
  17. if (ptd == NULL)
  18. {
  19. puts("Memory allocation failed. Goodbye.");
  20. exit(EXIT_FAILURE);
  21. }
  22. /* ptd now points to an array of max elements */
  23. puts("Enter the values (q to quit):");
  24. while (i < max && scanf("%lf", &ptd[i]) == 1)
  25. ++i;
  26. printf("Here are your %d entries:\n", number = i);
  27. for (i = 0; i < number; i++)
  28. {
  29. printf("%7.2f ", ptd[i]);
  30. if (i % 7 == 6)
  31. putchar('\n');
  32. }
  33. if (i % 7 != 0)
  34. putchar('\n');
  35. puts("Done.");
  36. free(ptd);
  37. return 0;
  38. }