Reputation: 189
I'm trying to access the variable name of the Reservation struct like this hotel[SomeIndex].reservations[AnotherIndex].name but it's not working.
How can I access those variables to fill the structure?
PS: It compiles,but it shows in debugger 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;
}
Upvotes: 0
Views: 1112
Reputation: 14382
You do not correctly initialize the reservations. Doing this correctly with raw pointers is hard and error-prone, and absolutely not recommended in C++.
First of all, use an std::vector<Hotel>
instead of a raw array Hotel *
. Vectors are the normal C++ "array" objects.
You can then replace the raw Reservation *
pointer inside the Hotel
struct with a std::vector<Reservation>
as well.
This makes it much easier to fix the actual error: The missing initialization.
What you did was create 20 hotels, then create 10 reservations for the first hotel! Then you try to access reservations for the 9th hotel, where there is an uninitialized pointer which points to random data. This means the behaviour is undefined: In this case, a segmentation fault is the way that your system shows you that you are accessing data which doesn't belong to you.
You need a loop to create reservations for each of the hotels, or if you just want to create reservations in the 9th hotel, you need to specify its index.
Using std::vector
is very simple:
#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".
};
And then you can just create reservations for the correct hotel:
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;
}
Upvotes: 1
Reputation: 18972
hotel->reservations=new Reservation[10];
is equivalent to hotel[0].reservations=new Reservation[10];
. You've initialised hotel[0]
but none of the other elements of hotel
- specifically not hotel[9]
.
It looks like what you need is to define constructors for Hotel
and Reservation
that initialise all their members to well-defined values.
And I would strongly suggest you use std::vector
rather than raw arrays; arrays are an advanced feature and very easy to go wrong with.
Upvotes: 1