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

C++ 创建邻接列表时出现分段错误,c++,pointers,struct,C++,Pointers,Struct,我正在为图形结构创建一个邻接列表 当我在gdb中运行时,给出了“程序接收信号SIGSEGV,分段错误。std::_List_node_base::hook()”错误。谁能指出代码中的错误吗 struct graph{ list<int> vertex; }*v; list<int>::iterator it; cin>>num_vertices; v = new graph[num_vertices]; if (v == 0) cout

我正在为图形结构创建一个邻接列表 当我在gdb中运行时,给出了“程序接收信号SIGSEGV,分段错误。std::_List_node_base::hook()”错误。谁能指出代码中的错误吗

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<<"->";
结构图{ 列表顶点; }*五,; 列表::迭代器; cin>>顶点数; v=新图[num_顶点]; 如果(v==0) 不能连接数; 对于(j=1;j>m; (v+i)->顶点向后推(m); } } 对于(i=1;ivertex.begin();it!=(v+i)->vertex.end();it++)
cout我没有发现任何错误,我编译了你的程序(刚刚声明了你正在使用的变量),它工作正常

#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<<"->";

}
#包括
#包括
使用名称空间std;
结构图{
列表顶点;
}*五,;
int main()
{
int num_顶点=0;
int num_connected=0;
列表::迭代器;
cin>>顶点数;
v=新图[num_顶点];
如果(v==0)
不能连接数;
对于(int j=1;j>m;
(v+i)->顶点向后推(m);
}
}
对于(inti=0;ivertex.begin();it!=(v+i)->vertex.end();it++)

coutC++数组是基于零的,因此应该使用
[0]
[num\u顶点-1]
对其进行索引。如果将循环从0更改为num\u顶点-1

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

for(i=0;i您是否尝试在gdb中一步一步地运行它以查看哪一行导致错误?您可以在gdb中使用
backtrace
或简单地使用
bt
来查看导致错误的调用。不要使用
v+i
,使用
v[i]
如果我从1而不是0初始化I循环,代码将不起作用@rishabh,这是正确的,因为数组索引运行[0,n)而不是[1,n]。感谢您指出错误。如果您能告诉我这是否是制作邻接列表的好方法,我将非常高兴。@rishabh,这是一个完全不同的问题,请单独发布