gpt4 book ai didi

c++ - 在结构中访问 std::list 会引发段错误

转载 作者:行者123 更新时间:2023-11-30 01:39:11 26 4
gpt4 key购买 nike

我目前无法从以下程序中找到段错误的来源。

struct info
{
std::list<int> bfs;
int *level;
int *distance;
};

...

info* Graph::BFS(int s)
{
info *tmp = (info*) malloc(sizeof(struct info));
tmp->level = new int[V];
tmp->distance = new int[V];

...

tmp->bfs.push_back(s); !! <- causes a segmentation fault
tmp->level[s] = 0; <- seems to work ok

int current;
std::list<int>::iterator i;
while (!myqueue.empty())
{
current = myqueue.front();
myqueue.pop();
tmp->bfs.push_back(current); <- causes segmentation fault

....

return tmp;
}

我也尝试过以下操作,但没有成功:

info *tmp = (info*) malloc(sizeof(struct info));
std::list<int> bsf;
tmp->bsf = bsf // and then call tmp->bsf.push_back()....

最佳答案

问题在于混合使用 C++ 代码和 C 代码。

在这个声明中

info *tmp = (info*) malloc(sizeof(struct info));

为结构分配内存而不调用其数据成员的构造函数,

而不是 malloc你必须使用运算符 new .否则数据成员 std::list<int> bfs;不会 build 。

关于c++ - 在结构中访问 std::list 会引发段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46229391/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com