[英]How to Access an array Struct Inside an array Struct in C++?
我正在嘗試像此酒店一樣訪問Reservation結構的變量名[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;
}
hotel->reservations=new Reservation[10];
相當於hotel[0].reservations=new Reservation[10];
。 你已經初始化hotel[0]
但沒有其他元素的hotel
-特別是不hotel[9]
您似乎需要為Hotel
and Reservation
定義構造函數,以將其所有成員初始化為定義明確的值。
我強烈建議您使用std::vector
而不是原始數組; 數組是一項高級功能,非常容易出錯。
您沒有正確初始化預留。 用原始指針正確地做到這一點很難而且容易出錯,在C ++中絕對不建議這樣做。
首先,使用std::vector<Hotel>
而不是原始數組Hotel *
。 向量是普通的C ++“數組”對象。
然后,您也可以用std::vector<Reservation>
替換Hotel
結構中的原始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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.