c++ - 如何在 C++ 中访问数组结构内部的数组结构?

标签 c++ arrays struct

我正在尝试访问 Reservation 结构的变量名称,就像这个 hotel[SomeIndex].reservations[AnotherIndex].name 但它不起作用。

如何访问这些变量来填充结构?

PS:编译成功,但在调试器中显示 Segmentation Fault。

struct Reservation{
string name;
};

struct Hotel {
string name;
Reservation *reservations;
};



int main()
{
    struct Hotel *hotel;
    hotel = new Hotel[20];
    hotel->reservations=new Reservation[10];


    hotel[9].name="Olympus Plaza";
    hotel[9].reservations[5].name="John Doe";

    cout<<"Hotel: "<<hotel[9].name<<" Name: "<<hotel[9].reservations[5].name<<endl;

return 0;   
}

最佳答案

您没有正确初始化预留。使用原始指针正确执行此操作很困难且容易出错,绝对不建议在 C++ 中使用。

首先,使用 std::vector<Hotel>而不是原始数组 Hotel * . vector 是普通的 C++“数组”对象。

然后您可以替换原始的 Reservation * Hotel 内的指针带有 std::vector<Reservation> 的结构

这使得修复实际错误变得容易得多:缺少初始化。

您所做的是创建 20 家酒店,然后为第一家酒店创建 10 个预订!然后您尝试访问第 9 家酒店的预订,其中有一个指向随机数据的未初始化指针。这意味着行为是未定义的:在这种情况下,段错误是您的系统向您显示您正在访问不属于您的数据的方式。

您需要一个循环来为每个酒店创建预订,或者如果您只想在第 9 家酒店创建预订,则需要指定其索引。

使用 std::vector很简单:

#include <vector>

struct Reservation {
    string name;
};

struct Hotel {
    string name;
    vector<Reservation> reservations;
    // if you have no "using namespace std", then it's "std::vector".
};

然后您可以为正确的酒店创建预订:

int main()
{
    vector<Hotel> hotel(20);
    hotel[9].reservations.resize(10);

    hotel[9].name="Olympus Plaza";
    hotel[9].reservations[5].name="John Doe";

    cout<<"Hotel: "<<hotel[9].name<<" Name: "<<hotel[9].reservations[5].name<<endl;

    return 0;   
}

关于c++ - 如何在 C++ 中访问数组结构内部的数组结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37550549/

相关文章:

c++ - MATLAB R2016b - MEX 无法编译 C++ 代码

c++ - 如何避免链接不必要的共享库?

c++ - Vulkan Dynamic Loader-函数调用上的访问冲突

c - 将一个结构体分配给 C 结构体中的另一个结构体

c++ - 在结构中分配数组字段

c++ - C++11 是否允许在标识符中使用美元符号?

arrays - 内置函数的运行时间

arrays - 如何从数组中提取整数值(混合类型 : integers/strings) via RegExp?

javascript - 将数组中的数据连接到对象以通过中间人转换其值

mongodb - 模型结构中的嵌套文档