Answer :
To write a function that dynamically allocates an array of integers. The function should accept an integer argument indicating the number of elements to allocate.
What is function?
Every programming language allows you to write code blocks that, when called, perform tasks. Consider a dog who only performs the same trick when asked. Except that you don't need dog treats to get your code to work. These code blocks are known as functions in programming.
Input and output are provided by all programming functions. The function contains instructions for producing output from its input. It's analogous to a cow eating grass (the input), which its body converts into milk, which a dairy farmer then milks (the output).
//CODE//
#include <iostream>
using namespace std;
// Function Prototype
//*********************************************
// Function arrayAllocator *
// This function dynamically allocates an *
// array of ints. The number of elements is *
// passed as an argument into the parameter *
// num. The function returns a pointer to the *
// array. *
//*********************************************
int* arrayAllocator(int);
// this is the function which you asked in the question
// Function definition for arrayAllocator
// This function takes number of elements to be put in array as arguement
// This function allocates memory dynamically based on arguement provided by user
// here arguement 'x' represents number of elements in array
// this function will dynamically allocate space for 'x' integers
// this function returns pointer to first element of the allocated space
// suppose the value of x is 10
// then continous space for 10 integers will be reserved and pointer to first element will be returned
// this dynamic memeory allocation in c++ is done using 'new' keyword
int* arrayAllocator(int x)
{
// here we are dynamically allocating space for x integers using new keyword
// this returns pointer to first element
int *p = new int[x];
// we will return the pointer from this function
return p;
}
int main()
{
int numElements; // To hold the number of elements to allocate
int *pointer; // A pointer to the array
int i; // A loop counter
// Get the array size.
cout << "\nEnter an array size: " << endl;
cin >> numElements;
// Allocate the array.
// call the arrayAllocator function
// pass it number of elements in the array
// gets a pointer to first element of the array
pointer = arrayAllocator(numElements);
// Fill the array with values.
for (i = 0; i < numElements; i++)
pointer[i] = i;
// Display the values.
cout << "Here are the values in the array:\n";
for (i = 0; i < numElements; i++)
{
cout << "Element " << i << " has the value " << pointer[i] << endl;
}//end for
// Deallocate the array.
delete [] pointer;
pointer = 0;
// system("pause");
return 0;
}
Learn more about function
https://brainly.com/question/20476366
#SPJ4