创建邻接列表时出现分段错误

时间:2012-11-08 13:47:17

标签: c++ pointers struct

我正在为图结构创建一个邻接列表.Below是我的代码片段  我在gdb中运行时给出“程序接收信号SIGSEGV,分段错误。在std :: _ List_node_base :: hook()中的0x0040340f”错误。有人可以指出代码中的错误。

struct graph{
    list<int> vertex;
}*v;

list<int>::iterator it;
cin>>num_vertices;

v = new  graph[num_vertices];

if (v == 0)
    cout << "Error: memory could not be allocated";

for(i=1;i<=num_vertices;i++)
{
    cin>>num_connected;
    for(j=1;j<=num_connected;j++)
    {
        cin>>m;
        (v+i)->vertex.push_back(m);
    }
}
for(i=1;i<=num_vertices;i++)
    for(it= (v+i)->vertex.begin();it!= (v+i)->vertex.end();it++)
        cout<<*it<<"->";

2 个答案:

答案 0 :(得分:1)

C ++数组从零开始,因此应使用[0][num_vertices-1]进行索引。如果将循环更改为0到num_vertices-1

for(i=0;i<num_vertices;i++)

您的代码应该有效。

当前的失败可能是由解除引用(v+num_vertices)的循环的最后一次迭代引起的,这是你的数组之外的内存。写入你没有分配的记忆会给出未定义的行为,所以seg故障并不令人惊讶。

答案 1 :(得分:0)

我在这里看不出任何错误,我编译了你的程序(刚刚声明了你正在使用的变量)并且它工作正常

#include <iostream>
#include <list>

using namespace std;

struct graph{
        list<int> vertex;
}*v;

int main ()
{
    int num_vertices = 0;
    int num_connected = 0;

    list<int>::iterator it;
    cin>>num_vertices;

    v = new  graph[num_vertices];

    if (v == 0)
        cout << "Error: memory could not be allocated";

    for(int i=0;i<num_vertices;i++)
    {
        cin>>num_connected;
        for(int j=1;j<=num_connected;j++)
        {
            int m;

            cin>>m;
            (v+i)->vertex.push_back(m);
        }
    }
    for(int i=0;i<num_vertices;i++)
        for(it= (v+i)->vertex.begin();it!= (v+i)->vertex.end();it++)
            cout<<*it<<"->";

}