//Sam Partovi CS1A Ch. 9, P.537, #1
/*******************************************************************************
* ALLOCATE DYNAMIC ARRAY
* ____________________________________________________________
* This function dynamically allocates an array of integers based on the
* number of elements provided as an argument and returns a pointer to
* the newly allocated array.
* ____________________________________________________________
* INPUT
* numElements: Number of integers to allocate in the array
* OUTPUT
* arrayPtr: Pointer to the dynamically allocated array
*******************************************************************************/
#include <iostream>
using namespace std;
//Function prototype
int* allocateArray(int numElements);
int main() {
int numElements; //INPUT - Number of elements to allocate
//Prompt for the number of elements
cout << "Enter the number of elements to allocate: " << endl;
cin >> numElements;
//Validate input
while (numElements <= 0) {
cout << "Number of elements must be positive. Try again: ";
cin >> numElements;
}
//Call function to allocate array
int* arrayPtr = allocateArray(numElements);
//Initialize and display the array contents
for (int i = 0; i < numElements; i++) {
*(arrayPtr + i) = i + 1;
cout << *(arrayPtr + i) << " ";
}
cout << endl;
//Free allocated memory
delete[] arrayPtr;
return 0;
}
//*****************************************************************************
//Function definition for allocateArray: *
//This function dynamically allocates memory for an array of integers *
//based on the number of elements provided and returns a pointer to it. *
//*****************************************************************************
int* allocateArray(int numElements) {
//Allocate memory for the array
int* arrayPtr = new int[numElements];
return arrayPtr;
}