// Torrez, Elaine CS1A Chapter 9, P. 537, #1
/********************************************************************************************
*
* ALLOCATE INTEGER ARRAY
*
* ------------------------------------------------------------------------------------------
* This program demonstrates a function that dynamically allocates an array of integers.
* The program asks the user how many integers to store, allocates the array, allows the
* user to enter the values, and then displays the integers back to the user.
*
* ------------------------------------------------------------------------------------------
* INPUT
*
* numElems : Number of integers to store in the array
* values : Each integer value entered by the user
*
* OUTPUT
*
* values : The list of integers stored in the dynamically allocated array
*
********************************************************************************************/
#include <iostream>
using namespace std;
// FUNCTION PROTOTYPE
int *allocateArray(int size); // Dynamically allocates an int array and returns a pointer
int main ()
{
int numElems; // Number of elements to allocate
int *numbers = nullptr; // Pointer to the dynamically allocated array
// INPUT: Ask user how many integers the array should hold
cout << "How many integers would you like to store? ";
cin >> numElems;
// INPUT VALIDATION: Number of elements must be greater than 0
while (numElems <= 0)
{
cout << "Error: Number of elements must be greater than 0. Try again: ";
cin >> numElems;
}
// Call function to allocate the array
numbers = allocateArray(numElems);
// INPUT: Fill the array with user-entered integers
cout << "\nEnter " << numElems << " integer values:\n";
for (int index = 0; index < numElems; index++)
{
cout << "Value #" << (index + 1) << ": ";
cin >> *(numbers + index); // Store value using pointer notation
}
// OUTPUT: Display the integers stored in the array
cout << "\nYou entered:\n";
for (int index = 0; index < numElems; index++)
{
cout << "Element [" << index << "] = " << *(numbers + index) << endl;
}
// Free dynamically allocated memory
delete [] numbers;
numbers = nullptr;
return 0;
}
//*******************************************************************************
// allocateArray
//------------------------------------------------------------------------------
// This function accepts an integer argument indicating the number of elements
// to allocate. It dynamically allocates an array of integers of that size and
// returns a pointer to the first element of the array.
//*******************************************************************************
int *allocateArray(int size)
{
int *ptr = nullptr; // Pointer to the new array
// Dynamically allocate the array
ptr = new int[size];
return ptr; // Return pointer to the allocated array
}