fork download
  1. //Amari Mosley CSC5 Chapter 9, P. 537 #1
  2.  
  3. /********************************************************************
  4.  *
  5.  * Allocate Array
  6.  * _______________________________________________________________
  7.  *
  8.  * This program dynamically allocates an array of integers and
  9.  * returns a pointer to the dynamically allocated array.
  10.  *
  11.  *
  12.  * _______________________________________________________________
  13.  *
  14.  * INPUT
  15.  * numElements : Number of integers to allocate
  16.  * OUTPUT
  17.  * arrayPtr : Pointer to the dynamically allocated array
  18.  *
  19.  ********************************************************************/
  20. #include <iostream>
  21. using namespace std;
  22.  
  23. // Function Prototype
  24. int* allocateArray(int);
  25.  
  26. int main()
  27. {
  28. // INPUT
  29. int numElements;
  30.  
  31. // Initialize Program variables
  32. int* arrayPtr;
  33.  
  34. // Get the number of elements from the user
  35. cout << "Enter the number of elements to allocate: ";
  36. cin >> numElements;
  37.  
  38. // Dynamically allocate the array
  39. arrayPtr = allocateArray(numElements);
  40.  
  41. // Output Result
  42. if (arrayPtr != nullptr)
  43. {
  44. cout << "Array of " << numElements
  45. << " integers was successfully allocated." << endl;
  46.  
  47. // Free dynamically allocated memory
  48. delete[] arrayPtr;
  49. }
  50. else
  51. {
  52. cout << "Invalid number of elements." << endl;
  53. }
  54.  
  55. return 0;
  56. }
  57.  
  58. // Function to dynamically allocate an array of integers
  59. int* allocateArray(int numElements)
  60. {
  61. if (numElements <= 0)
  62. {
  63. return nullptr;
  64. }
  65.  
  66. return new int[numElements];
  67. }
Success #stdin #stdout 0s 5352KB
stdin
5
stdout
Enter the number of elements to allocate: Array of 5 integers was successfully allocated.