Thanks for the help guys! Given the program below; // Array Allocator #include <
ID: 3546567 • Letter: T
Question
Thanks for the help guys!
Given the program below;
// Array Allocator
#include <iostream>
using namespace std;
// Function Prototype
int* arrayAllocator(int);
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 << " Enter an array size: " << endl;
cin >> numElements;
// Allocate 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: ";
for (i = 0; i < numElements; i++)
cout << "Element " << i << " has the value " << *(pointer + i) << endl;
// Deallocate the array.
delete [] pointer;
pointer = 0;
return 0;
}
Write a function that dynamically allocates an array of integers. The function should accept an integer argument indicating the number of elements to allocate. The function should return a pointer to the array.
Explanation / Answer
// Array Allocator
#include <iostream>
using namespace std;
// Function Prototype
int* arrayAllocator(int numElements)
{
int *pointer_to_array = new int[numElements];
return pointer_to_array;
}
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 << " Enter an array size: " << endl;
cin >> numElements;
// Allocate 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: ";
for (i = 0; i < numElements; i++)
cout << "Element " << i << " has the value " << *(pointer + i) << endl;
// Deallocate the array.
delete [] pointer;
pointer = 0;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.