[英]Segmentation fault i cant figure out
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 : allMSgs是一个结构:
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 NUMBER_OF_MSGS为1000
loc is 0,1,2.... (less then 1000); loc为0,1,2 ....(小于1000);
help please 请帮助
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. 或为allMSgs
数组中的每个指针调用new。
Better yet though you could just use a std::vector
or other container, with std::vector<allMSgs> _msgs;
更好的是,尽管您可以仅使用std::vector
或其他容器,并使用std::vector<allMSgs> _msgs;
, which you can use like it was an array in most cases. ,您可以在大多数情况下像使用数组一样使用它。 You can initalise it with a size too. 您也可以使用大小来初始化它。
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
循环,该循环分配所有项目。
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
的数组,而不是将指针定义为allMSgs
。
allMSgs* _msgs;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.