dimanche 5 mars 2017

Dynamic allocation of list in STL and element insertion

The following code is ought to read a a number of nodes in a graph, and then a certain number of edges which will be introduced in a dynamically allocated list of adjacent nodes. For some reason the program halts when calling add_edge() function in read_graf(), and the IDE (aka cb) opens the main file for stl_list. Can anyone point out the problem? Thanks!

Here's the code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<list>
#define grafMAX 101

FILE *fin = fopen("grafin.txt","r");
FILE *fout = fopen("grafout.txt","w");

struct Graf{
    int nrV;
    std::list <int> *ad;
};

void init_graf(Graf g, int nr){
    g.nrV = nr;
    g.ad = new std::list <int> [g.nrV];//(std::list <int> *)malloc(g.nrV * sizeof(std::list <int>));
}

void add_edge(Graf g, int n1, int n2){
    g.ad[n1].push_back(n2);
    g.ad[n2].push_back(n1);
}

inline int min(const int a, const int b){
    if(a < b)
        return a;
    return b;
}

void read_graf(Graf g){
    int n,m;
    fscanf(fin,"%d%d",&n,&m);
    init_graf(g,n);
    while(m){
        int x,y;
        fscanf(fin,"%d%d",&x,&y);
        add_edge(g,x,y);
        --m;
    }
}

Here's an input: 10 - # of nodes 11 - # of edges to be read 1 2 1 3 1 10 2 4 3 4 3 5 5 6 5 7 6 7 7 8 7 9

Aucun commentaire:

Enregistrer un commentaire