I'm creating a program where my main calls a function that creates an array by getting user input and then sends back the pointer to the array back to main...
However, it seems that it's storing every array in the same memory location when I print out the value for the pointer. So when I call the function for a new array does it just overwrite in the same memory location? How do I keep this from happening? I thought a new function call would force it to create a new array...
Below is the code for the function that creates the array.
float *createArray (float totals[], int numTotals)
{
float *pointer;
for (int i = 0; i < numTotals; i++)
{
cout << "Enter total " << i+1 << ": ";
cin >> totals[i];
}
pointer = totals;
You need to allocate the array on the heap. then return the pointer from the function. The caller of the function would then need to remember to delete the array. I would recommend you learn how to use vectors instead, it's like a dynamic array that handles the memory allocation for you. You can pass them out of functions very easily and you don't risk creating memory leaks.
But here is an example of how to allocate an array on the heap and then delete it.
1 2 3 4 5 6 7 8 9 10
cout << "enter size for array: ";
int sz;
cin >> sz;
float* pArray = newfloat[sz];
//do something with array;
delete[] pArray;