Reputation: 2655
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?
Upvotes: 5
Views: 6191
Reputation: 21351
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.
Upvotes: 3
Reputation: 70526
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);
Upvotes: 3
Reputation: 11920
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;
....
}
Upvotes: 0
Reputation: 121971
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
});
}
Upvotes: 10