My assignment is to read a graph in this input format:
However, I keep getting segmentation faults when I run my program. I think my problem is when writing the graph but I can't seem to find out why. Can someone point me in the right direction, please?
Some more information: readGraph must use insertEdge to insert an edge. It is tempting to read three numbers per line, no matter what. On the last line, only one number will be read successfully. But programs tend to be modified, and, wherever it is not too much work, it is a good idea to be prepared for modifications. What if the program is changed so that there is more input after the graph? You don't want readGraph to read into the what comes after the graph.
Write readGraph so that it does not depend on the line containing just 0 to be the last thing in the input. That is easy to do. Read the first number and check it before you read the next two.
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;
}
I actually found the answer guys thanks to some good old print statements in GDB. In readGraph, the scanf first scans into the edge variable and storing the variable. Thus the next number read will not be the actual first number, resulting in an infinite loop (segmentation fault) because depending on the input, 0 is read as a part of a graph and is later never found. Simply changing the scan to scanf("%i%i", &v, &w); and using the already read u in insertEdge() will read the graph correctly.