Reputation: 16774
I have the following constructor:
Timing::Timing():
_numMes(INIT_NUMMES),_msgs(new allMSgs*[NUMBER_OF_MSGS])
{
cout<<"build timing OK\n";
}
allMSgs is a struct :
typedef struct AllMSgs
{
double msg;
Agent* dedicatedTo;
}allMSgs;
and the declaration of it is done like this:
allMSgs** _msgs;
but when i try to reach for a field in the array like this:
_msgs[loc]->dedicatedTo=agent->getPointsTo();
i get a segmentation fault.
NUMBER_OF_MSGS is 1000
loc is 0,1,2.... (less then 1000);
help please
Upvotes: 0
Views: 79
Reputation: 88711
You've made an array of pointers, but not set them to point anywhere valid yet. You either need to change it to be simply:
allMSgs* _msgs;
and:
new allMSgs[NUMBER_OF_MSGS]
Or call new for each pointer in the allMSgs
array.
Better yet though you could just use a std::vector
or other container, with std::vector<allMSgs> _msgs;
, which you can use like it was an array in most cases. You can initalise it with a size too.
Upvotes: 5
Reputation: 34704
You have only allocated the array itself. You need to allocate each and every item of the array too. In the constructor, add a for
loop that allocates all of the items.
for (int i = 0; i < NUMBER_OF_MSGS; i++)
_msgs[i] = new allMSgs();
You can also just define the array as an array of allMSgs
and not pointers to allMSgs
.
allMSgs* _msgs;
Upvotes: 1