To regather my knowledge of dynamic memory (after 2 weeks without a computer), I'm doing a small sorting program where the user enters the number of elements in an array, then a for loop allows the user to enter each individual value. Then the program will sort the array in ascending order.
I'm having trouble even getting my dynamic array to even store any data at all. Using debugging mode that starts right after the for loop to gather each element value, I see that my dynamic array doesn't actually have any individual elements, but has its one value which always captures the first value inputted. For instance if the user enters 5 for element 0, that is the value of
Array, regardless of what is inputted after the first element. There are no element values, only a value for Array itself. It irks me that I can't realize what's wrong with my code because I feel like I should still know this.
I feel like the problem has to do with how I am initializing my dynamic array, however I'm at a loss. It seems I'm doing everything right. Only it seems as if the dynamic array doesn't actually take my variable
n and set it to be the size of the array.
Here's my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
#include <iostream>
#include <cstdlib>
using namespace std;
#define NULL 0
int main()
{
float n = 0.0f; // size of array
int g = 0;
float temp = 0.0f; // variable to assign to number input
cout << "Enter an array size: ";
cin >> n;
float* Array = new float[n];
cout << endl;
for ( int i = 0; i < n; i++ ) // unneeded function to output size of array, will probably remove later
{
g = g + 1;
cout << g << endl;
}
for ( int i = 0; i < n; i++ )
{
// list current element, ask user to enter, save value entered
cout << "[" << i << "] = "; // [current element] = ?
temp = 0.0f;
cin >> temp;
Array[i] = temp; // assign number input to current element
}
delete[] Array; // delete memory
Array = NULL; // array is now NULL
}
| |