fork download
  1.  
  2. //Dione Torrevillas CS1A Chapter 9, P. 537, #1
  3. /*
  4. ********************************************************************
  5. ARRAY ALLOCATOR
  6. Description: Create a function that dynamically allocates an array
  7.   of integers and returns a pointer to the new array.
  8. INPUT: Number of elements and the values to store in the array.
  9. OUTPUT: The values stored in the dynamically allocated array.
  10. ********************************************************************
  11. */
  12. #include <iostream>
  13. using namespace std;
  14.  
  15. // Function prototype
  16. int *allocateArray(int);
  17.  
  18. int main()
  19. {
  20. int size;
  21. cout << "How many integers? ";
  22. cin >> size;
  23.  
  24. // Make sure the array size is valid.
  25. while (size <= 0)
  26. {
  27. cout << "Enter a number greater than 0: ";
  28. cin >> size;
  29. }
  30.  
  31. int *numbers = allocateArray(size);
  32.  
  33. // Store the user's numbers in the allocated array.
  34. for (int i = 0; i < size; i++)
  35. {
  36. cout << "Enter number " << i + 1 << ": ";
  37. cin >> *(numbers + i);
  38. }
  39.  
  40. cout << "Numbers in the array: ";
  41. for (int i = 0; i < size; i++)
  42. cout << *(numbers + i) << " ";
  43. cout << endl;
  44.  
  45. // Free the dynamically allocated memory.
  46. delete [] numbers;
  47. numbers = 0;
  48. return 0;
  49. }
  50.  
  51. // Create an integer array and return a pointer to it.
  52. int *allocateArray(int size)
  53. {
  54. return new int[size];
  55. }
  56.  
Success #stdin #stdout 0s 544KB
stdin
3 10 20 30
stdout
How many integers? Enter number 1: Enter number 2: Enter number 3: Numbers in the array: 10 20 30