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.

Edited 3 Years Ago by Reverend Jim: Fixed formatting

Lots of things messed up:

1>

if (numElements <= 0)
return NULL;

NULL is defined as (void*)0 and its not the right place of use.If you want to stop execution then do something meaningful as:

if (numElements <= 0)
{
cout<<"Illegal value for numElements";
return 1; //Signifying improper termination
}

2>

//Return a pointer to the array.
cout << "The array holds the numbers you entered: \n";
for (count = 0; count < numElements; count++)
{
cout << *values << " ";
values++;
}

Why on earth are you manipulating the base address of the array??? And after this executes the value will be pointing to the last element and then after it if you do

delete [] values;
values = 0; //makes elements NULL.

It is bound to give errors.

Instead do this:

//To output the array contents 
cout << "The array holds the numbers you entered: \n";
for (count = 0; count < numElements; count++)
{
cout << values[count] << " ";
}

then after it for deallocation of memory you can do

delete[] values;
values=NULL; //Even though this is not required
Comments
Yes :)
This article has been dead for over six months. Start a new discussion instead.