I know that a vector would solve all of my issues, but the chapter is on pointers and I have to make a dynamic array. The getSalesList function works as it should, but now i need the main function to actually iterate through the results. Problem is that I do not see a way to capture the array size for use with a 'for' loop, or any other way to make this work. Help is appreciated.
#include<iostream>
usingnamespace std;
double* getSalesList();
int main()
{
double *sales = nullptr; // declare sales pointer and init to null
sales = getSalesList();
//Want to put a for loop here to display array contents,
//but I have no way to tell main the size of the array to iterate through
delete[] sales;
sales = nullptr;
return 0;
}
double* getSalesList()
{
int numDays = 0;
double *array = nullptr;
cout << "How many days of sales will you be entering? ";
cin >> numDays;
array = newdouble[numDays];
for (int i = 0; i < numDays; i++)
{
cout << "Please enter the sales for position " << i + 1 << ": ";
cin >> *(array + i);
cout << endl;
}
return array;
}
#include<iostream>
usingnamespace std;
void getSalesList(double*& , int&); //declare the function like thisint main()
{
double *sales = nullptr; // declare sales pointer and int to null
int arraySize = 0;
getSalesList(sales, arraySize); // call the function like this
// use the arraySize in loop like this:
for(int x = 0; x < arraySize; ++x)
{
cout << "Element " << x + 1 << ": " << sales[x] << endl;
}
delete[] sales;
sales = nullptr;
return 0;
}
void getSalesList(double*& sales, int& arraySize)
{
int numDays = 0;
double *array = nullptr;
cout << "How many days of sales will you be entering? ";
cin >> numDays;
array = newdouble[numDays];
for (int i = 0; i < numDays; i++)
{
cout << "Please enter the sales for position " << i + 1 << ": ";
cin >> *(array + i);
cout << endl;
}
sales = array; // this changes affects the actual parameter passed
arraySize = numDays; // this changes affects the actual parameter passed
}
Thanks guys. Passing a ref parameter seems to be the most logical solution, however the question requires that a pointer to the array should be the return value of the getSalesList function.
Because of that, I am unable to pass another int to the func as a ref parameter. I seem to be stuck!
@jlb, a struct is something we have not covered yet, so I am unable to use it right now.
Wow. I attempted that before even posting the question, but my syntax was off. Ugh. Sorry to waste everyone's time! Thanks for pushing me back to my original idea.
I appreciate all the help from everyone. Take care!