The question is to write a function that dynamically allocates an array of integers. the function shoud accept an integer argument indicating the number of elements to allocate The function shoud return a pointer to the array
Here is what i have so far, and it kinda works but at the very end after it runs i get a program error.
#include <iostream>
using namespace std;
int main()
{
int numElements; // To hold the number of elements to allocate
int *values; // A pointer to the array
int count; // A loop counter
// Get the array size.
cout << "\nEnter an array size: " << endl;
cin >> numElements;
//Return null if num is zero or negative.
if (numElements <= 0)
return NULL;
// Allocate the array.
values = new int[numElements];
//Get the value for each element.
cout << "Enter the value of the elements below.\n";
for (count = 0; count < numElements; count++)
{
cout << "Value #" << (count + 1) << ": ";
cin >> values[count];
}
//Return a pointer to the array.
cout << "The array holds the numbers you entered: \n";
for (count = 0; count < numElements; count++)
{
cout << *values << " ";
values++;
}
//Free dynamically allocated memory.
delete [] values;
values = 0; //makes elements NULL.
return 0;
}
I can't figure out what im doing wrong, i believe i answered the question correctly but i can't find where i mest up on the code that keeps on getting me the error debug assertion failed. Could some one Please help. My instructor also suggested using // Allocate the array.
pointer = arrayAllocator(numElements);
instead of //Dynamically allocate the array
element = new int[num];
But i couldn't get his recommendation to work.