i am trying pass a struct array from a function. i searched a lot but was unable to find a way to this. below is the code i am tring.
struct menuItemType
{
int itemNo;
string menuItem;
double price;
};
void getData(menuItemType *menuList[10])
{
menuList[0]->itemNo = 111;
menuList[0]->menuItem = "Apple";
menuList[0]->price = 2.00;
....
menuList[0]->itemNo = 120;
menuList[0]->menuItem = "Chocolate";
menuList[0]->price = 5.00;
}
int main()
{
/* i know that i can't return a array. but i want to get the menuList[10] values here.
not sure which code i have to use..*/
}
Your void getData(menuItemType *menuList[10])
does not return anything. Instead, it fills the data in the memory pointed by input parameter.
int main()
{
menuItemType data[10];
getData(&data);
std::cout << data[9].menuItem << std::endl; // Chocolate
}
However, why are you insisting on using low level arrays? Use std::vector
instead.
std::vector<menuItemType> getData()
{
std::vector<menuItemType> data;
data.push_back({111, "Apple", 2.00});
...
data.push_back({120, "Chocolate", 5.00});
return std::move(data);
}
int main()
{
std::vector<menuItemType> data = getData();
std::cout << data[9].menuItem << std::endl; // Chocolate
}
It will print Chocolate
, because I assume there is a typo in your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.