Reputation: 115
I would like to know how to prototype a function that returns a array which also takes in an array. after prototyping the array how can i implement it
is this correct?
coffee* getData(*coffe);
int main() {
coffee cf[256];
coffee FinalCoffee[256];
FinalCoffee=getData(cf);
}
coffee getData(coffee objcf[]) {
for(int i=0;i<SIZE;i++) {
objcf[i].brand="nescafe";
}
return coffee;
}
Plsease do advice me on this. i need to be able to get back array so that i can pass the updated array to another function to process it.
Upvotes: 1
Views: 169
Reputation: 9144
You can do this in C++. References to the rescue. Ugly syntax ahead, typedefs are recommended:
#include <iostream>
using namespace std;
template<size_t N>
int (&f(int(&A)[N])) [N] {
for(auto& i: A) i +=10;
return A;
}
int main() {
int A[3] = {1,2,3};
auto& AA = f(A);
for(auto i: AA) cout << i << "\n";
}
But as, Konrad Rudolph noted, you actually do not need return anything from f(), your array is modified in place. And your function can be much simpler:
void f(int (&A)[N])
Upvotes: 4
Reputation: 545913
Your code doesn’t even have matching declaration and function definition. This doesn’t work.
But the following does:
std::vector<coffee> getData(std::vector<coffee> const& objs) {
std::vector<coffee> result;
// Do something to fill result
return result;
}
But if, as in your example, you want to manipulate the original array, rather than returning a new one, then it makes more sense to not have a return value at all, and to pass the argument as a non-const reference:
void manipulateData(std::vector<coffee>& objs) {
for (auto& obj : objs)
obj.brand = "nescafe";
}
As a rule of thumb, try to avoid C arrays in favour of C++ standard library containers. This will make your life much, much easier.
Upvotes: 5
Reputation: 409364
To start with, the declaration (prototype) and the definition (implementation) of the function headers are different:
coffee* getData(*coffe);
Versus
coffee getData(coffee objcf[])
The last one doesn't even return a pointer.
As for your question, your prototype says that getData
returns a pointer but you assign it to an array. This will not work. Instead declare FinalCoffee
as a pointer:
coffee cf[256];
coffee* FinalCoffee;
FinalCoffee=getData(cf);
However you don't really need that. When getData
modifies the array you pass as argument, then those modifications will be in the cf
array too as arrays are passed as references.
Upvotes: 2