5

In my main function I create an array of objects of a certain class "Menu"

And when I call a function I want to provide a pointer to that array.

Menu menu[2];
// Create menu [0], [1]
Function(POINTER_TO_ARRAY);

Question: What is the correct way to write the Function parameters?

I try:

Function(&menu);

and in Header file:

void Function(Menu *menu[]); // not working
error: Cannot convert parameter 1 from Menu(*)[2] to Menu *[]

void Function(Menu * menu); // not working
error: Cannot convert parameter 1 from Menu(*)[2] to Menu *[]

and I can't come up with any other way to do this and I can't find a solution to this particular problem.

Simply, I want to be able to access the Menu array within the function through a pointer. What are the difference in normal pointer to a pointer to an array?

4 Answers 4

10

Declaration:

void Function(Menu* a_menus); // Arrays decay to pointers.

Invocation:

Function(menu);

However, you would need to inform Function() how many entries are in the array. As this is C++ suggest using std::array or std::vector which have knowledge of their size, beginning and end:

std::vector<Menu> menus;
menus.push_back(Menu("1"));
menus.push_back(Menu("2"));

Function(menus);

void Function(const std::vector<Menu>& a_menus)
{
    std::for_each(a_menus.begin(),
                  a_menus.end(),
                  [](const Menu& a_menu)
                  {
                      // Use a_menu
                  });
}
Sign up to request clarification or add additional context in comments.

Comments

3

Either by const or non-const pointer

void Function(Menu const* menu);
void Function(Menu* menu);

...or by const or non-const reference

void Function(Menu const (&menu)[2]);
void Function(Menu (&menu)[2]);

which can be generalized to a template so that the array size will be deduced by the compiler:

template<size_t N> void Function(Menu const (&menu)[N]);
template<size_t N> void Function(Menu (&menu)[N]);

Always call as Function(menu);

Comments

3

Should work if you use

 void Function(Menu * menu); 

and call using

Function(menu);  

instead of

Function(&menu); 

passing the array name causes it to decay to a pointer to the type contained in the array. However, as @hmjd says in his answer you will also need to pass the array size, so his suggestion of using a vector is favourable if this option is open to you.

Comments

0

You can use

Function((void *) whatever_pointer_type_or_array_of_classes);

in your main.

And in the function:

type Function(void * whatever)
{
    your_type * x =(your_type *) whatever;
    //use x 
    ....
    x->file_open=true;
    ....
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.