fork download
  1. //Zachary Abdollahi CS1A Chapter 9, P. 538, #1
  2. //
  3. /*******************************************************************************
  4.  * ALLOCATE DYNAMIC INTEGER ARRAY
  5.  *______________________________________________________________________________
  6.  * This program prompts the user for the desired size of an integer array, calls
  7.  * a function that dynamically allocates an array of that size using a pointer,
  8.  * populates it with sequential values, and displays the contents before freeing
  9.  * memory.
  10.  *
  11.  * Computation is based on the formula:
  12.  * Element Value = Index + 1
  13.  * _____________________________________________________________________________
  14.  * INPUT
  15.  * arraySize : Number of integer elements to allocate
  16.  *
  17.  * OUTPUT
  18.  * arrayPtr : Pointer to dynamically allocate integer array
  19.  *
  20.  ******************************************************************************/
  21. #include <iostream>
  22. using namespace std;
  23.  
  24. // Function Prototype
  25. int *allocateArray(int);
  26.  
  27. int main()
  28. {
  29. int arraySize; //INPUT - Number of elements to allocate
  30. int *arrayPtr; //OUTPUT - Pointer to dynamic integer array
  31.  
  32. // Prompt User for Array Size
  33. cout << "Enter the number of elements to allocate: ";
  34. cin >> arraySize;
  35.  
  36. // Validate Positive Array Size
  37. while (arraySize <= 0)
  38. {
  39. cout << "Please enter a positive integer: ";
  40. cin >> arraySize;
  41. }
  42.  
  43. // Dynamically Allocate Array via Function
  44. arrayPtr = allocateArray(arraySize);
  45.  
  46. // Populate Array Using Pointer Arithmetic
  47. for ( int count = 0; count < arraySize; count++)
  48. {
  49. *(arrayPtr + count) = count + 1;
  50. }
  51.  
  52. // Output Array Elements
  53. cout << "\nAllocated Array Elements:\n";
  54. for (int count = 0; count < arraySize; count++)
  55. {
  56. cout << *(arrayPtr + count) << " ";
  57. }
  58. cout << endl;
  59.  
  60. // Free Dynamically Allocated Memory
  61. delete [] arrayPtr;
  62. arrayPtr = nullptr;
  63.  
  64. return 0;
  65. }
  66.  
  67. /******************************************************************************
  68.   * Function : allocateArray
  69.   * Dynamically allocates an array of integers of the specified size and returns
  70.   * a pointer to the allocated memory.
  71.   *****************************************************************************/
  72. int *allocateArray(int size)
  73. {
  74. int *ptr = new int [size];
  75. return ptr;
  76. }
Success #stdin #stdout 0s 544KB
stdin
5
stdout
Enter the number of elements to allocate: 
Allocated Array Elements:
1 2 3 4 5