1

Suppose we have:

struct elements{ string drink_name; double price_per_can; double number_in_machine; }; struct elements machine[6]; 

And machine is populated in main(). How do I pass machine into a function (by reference) to be used inside the function?

1
  • 2
    Consider using std::array instead of a naked fixed length array. Commented Dec 4, 2013 at 23:35

2 Answers 2

5

You can pass it as a reference:

void foo(elements (&x)[6]) { x[1].price_per_can = 1.8; x[4].drink_name = "mom's breakfast juice"; } int main() { elements machine[6]; foo(machine); } 
Sign up to request clarification or add additional context in comments.

3 Comments

Why am I passing elements into foo() instead of machine?
He probably meant machine.
@user3064097: Sorry, fixed.
1
std::array<elements, 6> machine_c2; // Edit: Removed const // Edit: Reflect edit by other user // and add consistency with machine.begin() void doSomething(std::array<elements, 6>& machine) { std::cout << machine.begin()->drink_name; machine.begin()->drink_name = "Cherry"; } int main() { machine_c2.begin()->drink_name = "Strawberry"; doSomething(machine_c2); std::cout << machine_c2.begin()->drink_name; return 0; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.