//Maxwell Brewer CS1A Chapter 9, p. 537, #1
//
/*******************************************************************************
* ARRAY ALLOCATOR
* _____________________________________________________________________________
* This program dynamically allocates an array of integers based on a
* pre-determined number of elements. After allocation, it initializes
* each element in the array with a value, demonstrates usage by printing the
* values, and then deallocates the memory to prevent memory leaks.
* _____________________________________________________________________________
* INPUT
* numElements : Number of elements the user wishes to allocate for the array.
*
* OUTPUT
* Array values : Displays each element in the array after initializing it.
*
* ****************************************************************************/
#include <iostream>
using namespace std;
int *arrayAllocator(int numElements){
//first check if argument is 0 or negative
if(numElements <= 0){
//in this case return a null pointer
return nullptr;
}
//otherwise, dynamically allocate memory
//for an array of specified size
int *ptr = new int[numElements];
//return the created pointer
return ptr;
}
int main() {
int numElements = 70;
int* myArray = arrayAllocator(numElements);
if (myArray != nullptr) {
// Use the array (example)
for (int i = 0; i < numElements; i++) {
myArray[i] = i * 2;
}
// Print the array
for (int i = 0; i < numElements; i++) {
cout << myArray[i] << " ";
}
cout << endl;
// Deallocate memory
delete[] myArray;
} else {
cerr << "Array allocation failed or invalid size." << endl;
}
return 0;
}