[英]Return struct array from function c++
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.您的
void getData(menuItemType *menuList[10])
不返回任何内容。 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
。
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.它将打印
Chocolate
,因为我认为您的代码中有错字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.