graph - Segmentation Fault C++ -
the input in following format
5 1 2 9.0 1 3 12.0 2 4 18.0 2 3 6.0 2 5 20.0 3 5 15.0 0 1 5
the first number number of vertexes in graph. next lines 0 edges of graph. first , second numbers being vertexes , third being how far edge between them. trying read in data , store edges there locations in list adjacency vertex. example make graph 5 vertexes edges 1 2&3. 2 4&3&1 etc.
i getting segmentation fault after entering 4 numbers. fault happening on line mygraph.vertexinfo[p1].adjacency -> vertex=p2; starts trying store information. why getting fault?
#include <cstdio> using namespace std; struct listcell { listcell* next; int vertex; double weight; listcell(int v, double w, listcell* nxt) { vertex = v; weight = w; next = nxt; } }; typedef listcell* list; struct vertex { bool signaled; long distance; list adjacency; }; struct graph { int numvertices; vertex* vertexinfo; graph(int n) { numvertices = n; vertexinfo = new vertex[n+1]; for(int = 1; <= n; i++) { vertexinfo[i].signaled = false; } } }; //============================================================== // readin //============================================================== // //============================================================== void readin() { int g; int p1; int p2; float edge; scanf("%i ", &g); graph mygraph(g); scanf("%i", &p1); while(p1 != 0) { scanf("%i", &p2); scanf("%f", &edge); mygraph.vertexinfo[p1].adjacency -> vertex=p2; mygraph.vertexinfo[p2].adjacency -> vertex=p1; mygraph.vertexinfo[p1].adjacency -> weight=edge; mygraph.vertexinfo[p2].adjacency -> weight=edge; scanf("%i", &p1); } } //============================================================== // main //============================================================== int main(int argc, char** argv) { readin(); return 0; }
let's @ adjacency
is:
struct vertex { bool signaled; long distance; list adjacency; };
and let's @ list
is:
typedef listcell* list;
so, adjacency
pointer listcell
. that's fine, can work that. before can, must make sure adjacency
points something. question becomes adjacency
point in code?
the answer is: knows? never make point anything, it's pointing somewhere randomly. , happens when try write random area of memory? well, if you're lucky, crash.
so, how solve problem? simple: initialize , manipulate adjacency
correctly. may wish dynamic memory allocation in c++ , standard library provides rather nifty , working implementation of linked list.
sidenote: seem treat adjacency
linked list. however, ought note adjacency
pointer node in linked list. again, great time learn std::list
.
Comments
Post a Comment