Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function parameter: Pointer to array of objects

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?

like image 949
Deukalion Avatar asked Aug 08 '12 14:08

Deukalion


1 Answers

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
                  });
}
like image 64
hmjd Avatar answered Sep 25 '22 15:09

hmjd