Seg Fault

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <fstream>

using namespace std;

struct NODE{
 int outdeg;
 int *adjNodes;
};

const int MAX = 20;
NODE nodes[MAX];

void readInput();
int numNodes;

int main(){
 readInput();
}

void readInput(){
 ifstream infile;
 int nodeNum;
 string dummy;

 infile.open("nodes.dat");
 infile >> numNodes;
 getline(infile,dummy);
 NODE *nodes = new NODE[numNodes];
 for (int i = 0; i < 2; i++){
     infile >> nodeNum;
     getline(infile,dummy, '(');
     getline(infile,dummy, ' ');
     infile >> nodes[i].outdeg;
     getline(infile, dummy, ' ');
//     for (int j = 0; j < nodes[i].outdeg; j++)
//          infile>>nodes[i].adjNodes[j];
//     getline(infile,dummy);
 }
}


Input
1
2
3
14 //numNodes
0 ( 3): 5 9 10 //node (outdegree) and nodes adjacent to
1 (10): 0 5 8 10 9 7 6 11 12 13 //no particular order 


Having a problem reading this input, I know it's a terribly inefficient way to do it but it works. My problem is that line 37 is causing a segmentation fault and I don't know why.The outdegree and node number are being read correctly but when i try to get adjnodes it causes a seg fault. I think I'm declaring the array incorrectly but can anyone help? Thanks
That is because on line 8, adjNode is a pointer. So for you to use it, you have to initialise it. The way to do this is to use the new keyword/constructor/allocator.

so
nodes[i].adjNodes = new int[nodeNum];

infile >> nodes[i].adjNodes[j];
Last edited on
Thanks! It worked.

Topic archived. No new replies allowed.