allocating space to list pointers using malloc not working

后端 未结 1 836
野性不改
野性不改 2020-12-22 10:08
class graph
{

    int v;
    list *adj;
    void dfsutil(int v,bool visited []);
    public:
    graph(int v)
    {
        this->v=v;
        //adj =         


        
相关标签:
1条回答
  • 2020-12-22 10:16

    You did not create an array of std::list objects when you used malloc. All malloc does is allocate memory from the heap -- no objects are created. Thus attempting to use your std::list's as if they are created correctly will result in undefined behavior.

    You should use a container such as std::vector to store your list objects:

    #include <vector>
    #include <list>
    
    class graph
    {
        int v;
        std::vector<std::list<int>> adj;
        void dfsutil(int v,bool visited []);
        public:
            graph(int num) : v(num), adj(num) {}
        void addedge(int v,int w);
        void dfs(int v);
    };
    

    Note there is no need to allocate memory. The rest of your code should stay the same, since vector has an overloaded operator [] to access the items.

    0 讨论(0)
提交回复
热议问题