Arrays cannot be returned (they decay to a pointer and the array goes out of scope and becomes invalid before anyone can use the returned pointer) and cannot be assigned to a new array variable if you could return the array. This puts a serious damper on passing arrays around.
The modern solution is to use Library Containers such as std::array
and std::vector
. Sadly many introductory courses do not allow the student to use std::vector
for good or ill, so the student has to find other ways to get the same effect.
So... You cannot return an array, but you can return a structure containing an array.
struct arrayholder
{
int numObjectsArr[10];
int used = 0; // Book keeping for much of the array is in use
}
Now we can
arrayholder numObjects ()
{
int i;
arrayholder Arr;
cout << "Enter number of objects, ranging from 1 to 10 objects: ";
return Arr
}
This doesn't do anything useful yet, but at least we can get the array out of the function. There is a downside to this, returning the structure by value means the structure will be copied. Fortunately any decent compiler today will support Copy Elision and silently save you all the extra overhead.
How do we get data into the array?
arrayholder numObjects ()
{
int i;
arrayholder Arr;
cout << "Enter number of objects, ranging from 1 to 10 objects: ";
while (!(cin >> Arr.used)) // keep asking for a number until we get a number
{
// didn't get a number. This sets an error flag that needs to be cleared
cin.clear();
//throw out the bad input
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
// note: the above is about the minimum you want to use for input validation.
// there are a bunch pf potential problems with it, like allowing crap like "8foo foo"
// add logic to keep nagging the users until they give a number from 1 to 10
// I'm not writing this because it's the crux of the assignment.
for (int index = 0; index < Arr.used; index++)
{
while (!(cin >> Arr.numObjectsArr[index]))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
return Arr;
}
See that horrible block of repeated code? It's a perfect candidate to be replaced with a function.
int getNumber()
{
int num;
while (!(cin >> num))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
return num;
}
arrayholder numObjects ()
{
int i;
arrayholder Arr;
cout << "Enter number of objects, ranging from 1 to 10 objects: ";
Arr.used = getNumber();
// add logic to keep nagging the users until they give a number from 1 to 10
// I'm still not writing this because it's the crux of the assignment, but
// getNumber just made it a lot easier to write.
for (int index = 0; index < Arr.used; index++)
{
Arr.numObjectsArr[index] = getNumber();
}
return Arr;
}