Function parameter: pointer to an array of objects

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

And when I call the function, I want to provide a pointer to this array.

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

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

I'm trying to:

Function(&menu);

and in the 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 cannot think of another way to do this, and I cannot find a solution to this particular problem.

I just want to have access to the menu array inside the function using a pointer. What is the difference in a normal pointer to an array pointer?

+5
source share
4 answers

Declaration:

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

Vocation:

Function(menu);

Function(), . ++, std::array std::vector , :

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
                  });
}
+9

const const

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

...

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

, :

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

Function(menu);

+3

,

 void Function(Menu * menu); 

Function(menu);  

Function(&menu); 

, . , @hmjd, , , .

+3

Function((void *) whatever_pointer_type_or_array_of_classes);

.

:

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

All Articles