//Zachary Abdollahi CS1A Chapter 9, P. 538, #1
//
/*******************************************************************************
* ALLOCATE DYNAMIC INTEGER ARRAY
*______________________________________________________________________________
* This program prompts the user for the desired size of an integer array, calls
* a function that dynamically allocates an array of that size using a pointer,
* populates it with sequential values, and displays the contents before freeing
* memory.
*
* Computation is based on the formula:
* Element Value = Index + 1
* _____________________________________________________________________________
* INPUT
* arraySize : Number of integer elements to allocate
*
* OUTPUT
* arrayPtr : Pointer to dynamically allocate integer array
*
******************************************************************************/
#include <iostream>
using namespace std;
// Function Prototype
int *allocateArray(int);
int main()
{
int arraySize; //INPUT - Number of elements to allocate
int *arrayPtr; //OUTPUT - Pointer to dynamic integer array
// Prompt User for Array Size
cout << "Enter the number of elements to allocate: ";
cin >> arraySize;
// Validate Positive Array Size
while (arraySize <= 0)
{
cout << "Please enter a positive integer: ";
cin >> arraySize;
}
// Dynamically Allocate Array via Function
arrayPtr = allocateArray(arraySize);
// Populate Array Using Pointer Arithmetic
for ( int count = 0; count < arraySize; count++)
{
*(arrayPtr + count) = count + 1;
}
// Output Array Elements
cout << "\nAllocated Array Elements:\n";
for (int count = 0; count < arraySize; count++)
{
cout << *(arrayPtr + count) << " ";
}
cout << endl;
// Free Dynamically Allocated Memory
delete [] arrayPtr;
arrayPtr = nullptr;
return 0;
}
/******************************************************************************
* Function : allocateArray
* Dynamically allocates an array of integers of the specified size and returns
* a pointer to the allocated memory.
*****************************************************************************/
int *allocateArray(int size)
{
int *ptr = new int [size];
return ptr;
}