为什么试图编写图形时出现分割错误?

问题描述 投票:2回答:2

我的任务是以这种输入格式读取图形:enter image description here

并以这种格式输出enter image description here

但是,在运行程序时,我总是遇到分段错误。我认为我的问题在于编写图表时,但我似乎找不到原因。有人可以指出我正确的方向吗?

更多信息:readGraph必须使用insertEdge插入边。无论如何,每行读取三个数字很诱人。在最后一行,将仅成功读取一个数字。但是程序往往会被修改,并且在工作量不大的地方,为修改做准备是个好主意。如果更改了程序以便在图形之后有更多输入,该怎么办?您不希望readGraph读入图形后面的内容。

编写readGraph,以使其不依赖于仅包含0的行成为输入中的最后一件事。那很容易做到。阅读第一个数字并检查它,然后再阅读下两个。

 struct Edge
    {
        int vertex1;
        int vertex2;
        int weight;

        Edge()
        {
            vertex1 = 0;
            vertex2 = 0;
            weight = 0;
        }
    };

    struct Graph
    {
        int numOfVertices;
        int numOfEdges;
        Edge*   edges;
        int sizeOfArray;

        Graph(int n, int e)
        {
            numOfVertices = n;
            numOfEdges = 0;
            sizeOfArray = e;
            edges = new Edge[e];
        }
    };

    //Inserts an edge between vertices u and v, of weight w, into graph g.
    void insertEdge(int u, int v, int w, Graph* g)
    {
        Edge e;
        e.vertex1 = u;
        e.vertex2 = v;
        e.weight = w;
        g->edges[g->numOfEdges] = e;
        g->numOfEdges++;

    }

    //Reads vertices, edges, and weight from the input
    //and allocates a graph in the heap with enough room for e edges.
    Graph* readGraph(int e)
    {
        int numberOfVertices, edge;
        scanf("%i", &numberOfVertices);
        Graph* g = new Graph(numberOfVertices, e);
        int u, v, w;
        while(scanf("%i", &edge) != 0)
        {

            scanf("%i%i%i", &u, &v, &w);
            insertEdge(u,v,w,g);
        }
        return g;
    }

    //Writes graph g by listing the number of vertices and the number of edges.
    void writeGraph(const Graph* g)
    {
        printf("There are %i vertices and %i edges", g->numOfVertices, g->numOfEdges);
        printf("Vertices        Weight");
        for(int i = 0; i < g->numOfEdges; i++)
        {
            printf(" %i %i      %i", g->edges[i].vertex1, g->edges[i].vertex2, g->edges[i].weight);
        }

    }

    int main()
    {  

        int maxEdges = 1000;
        Graph* g = readGraph(maxEdges);
        writeGraph(g);
        return 0;
    }
c++ graph structure
2个回答
2
投票

我看不到您的代码中的问题,但也许我是盲目的。但是,您可以使用gdb进行调试。 15分钟的精心投资分钟:https://www.youtube.com/watch?v=PorfLSr3DDI

或者您可以使用Valgrind之类的工具:https://valgrind.org/https://valgrind.org/docs/manual/quick-start.html

祝你最好。


0
投票

我实际上找到了答案的人,这要归功于GDB中一些不错的旧打印语句。在readGraph中,scanf首先扫描到edge变量并存储该变量。因此,下一个读取的数字将不是实际的第一个数字,从而导致无限循环(分段故障),因为根据输入,将0读取为图形的一部分,但以后再也找不到它。只需将扫描更改为scanf(“%i%i”,&v,&w);并使用insertEdge()中已读取的u可以正确读取图形。

© www.soinside.com 2019 - 2024. All rights reserved.