从函数c ++返回struct数组

时间:2016-04-21 15:38:03

标签: c++ arrays function struct

我正在尝试从函数传递结构数组。我搜索了很多,但无法找到解决方法。下面是我正在考虑的代码。

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..*/
}

1 个答案:

答案 0 :(得分:2)

您的void getData(menuItemType *menuList[10])不会返回任何内容。相反,它填充输入参数指向的内存中的数据。

int main()
{
    menuItemType data[10];
    getData(&data);
    std::cout << data[9].menuItem << std::endl; // Chocolate
}

但是,为什么要坚持使用低级数组呢?请改用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
}

它将打印Chocolate,因为我认为您的代码中存在拼写错误。

相关问题