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. // Create an integer array and return a pointer to it.
  16. int *allocateArray(int size)
  17. {
  18. return new int[size];
  19. }
  20.  
  21. int main()
  22. {
  23. int size;
  24. cout << "How many integers? ";
  25. cin >> size;
  26.  
  27. // Make sure the array size is valid.
  28. while (size <= 0)
  29. {
  30. cout << "Enter a number greater than 0: ";
  31. cin >> size;
  32. }
  33.  
  34. int *numbers = allocateArray(size);
  35.  
  36. // Store the user's numbers in the allocated array.
  37. for (int i = 0; i < size; i++)
  38. {
  39. cout << "Enter number " << i + 1 << ": ";
  40. cin >> *(numbers + i);
  41. }
  42.  
  43. cout << "Numbers in the array: ";
  44. for (int i = 0; i < size; i++)
  45. cout << *(numbers + i) << " ";
  46. cout << endl;
  47.  
  48. // Free the dynamically allocated memory.
  49. delete [] numbers;
  50. numbers = nullptr;
  51. return 0;
  52. }
  53.  
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