How do I fix these errors from creating a graph using an adjacenct list?

  adjacency-list, c++, graph, pointers

I want to make a C++ program on creating a graph using an adjacent list.

So I made this:

#include<bits/stdc++.h>

using namespace std;

struct listNode{

     int vertexNumber;
     listNode *next;

};

struct graph{

    int v;
    int e;
    listNode*adj;   
};


struct graph *adjListofGraph(){

    int i,x,y;
    listNode *temp;
    graph *g = (graph*)malloc(sizeof(graph));
    if(!g){
        cout<<"memory error";
        return NULL;
    }
    cout<<"Enter Number of vertices and Number of edges: ";
    cin>>g->v>>g->e;
    g->adj = (listNode**)malloc(g->v * sizeof(listNode));
    for(i=0;i<g->v;i++){
        g->adj[i] = (listNode*)malloc(sizeof(listNode));
        g->adj[i]->vertexNumber = i;
        g->adj[i]->next = g->adj[i];
    }
    for(int i=0;i<g->e;i++){
        cin>>x>>y;
        temp = (listNode*)malloc(sizeof(listNode));
        temp->vertexNumber = y;
        temp->next = g->adj[x];
        g->adj[x]->next = temp;
        temp = (listNode*)malloc(sizeof(listNode));
        temp->vertexNumber = x;
        temp->next = g->adj[y];
        g->adj[y]->next = temp; 
    }
    cout<<endl;
    return g;
}

int main(){ 

    graph *G = adjListofGraph();
}

But for some reason, I get these errors:

graph1.cpp: In function ‘graph* adjListofGraph()’:

graph1.cpp:25:53: error: cannot convert ‘listNode**’ to ‘listNode*’ in assignment
g->adj = (listNode**)malloc(g->v * sizeof(listNode));
^
graph1.cpp:27:49: error: no match for ‘operator=’ (operand types are ‘listNode’ and ‘listNode*’)
g->adj[i] = (listNode*)malloc(sizeof(listNode));
^

graph1.cpp:4:8: note: candidate: ‘constexpr listNode& listNode::operator=(const listNode&)’
struct listNode{
^~~~~~~~

graph1.cpp:4:8: note: no known conversion for argument 1 from ‘listNode*’ to ‘const listNode&’

graph1.cpp:4:8: note: candidate: ‘constexpr listNode& listNode::operator=(listNode&&)’

graph1.cpp:4:8: note: no known conversion for argument 1 from ‘listNode*’ to ‘listNode&&’

graph1.cpp:28:12: error: base operand of ‘->’ has non-pointer type ‘listNode’
g->adj[i]->vertexNumber = i;
^~

graph1.cpp:29:12: error: base operand of ‘->’ has non-pointer type ‘listNode’
g->adj[i]->next = g->adj[i];
^~

graph1.cpp:35:24: error: cannot convert ‘listNode’ to ‘listNode*’ in assignment
temp->next = g->adj[x];
^

graph1.cpp:36:12: error: base operand of ‘->’ has non-pointer type ‘listNode’
g->adj[x]->next = temp;
^~

graph1.cpp:39:24: error: cannot convert ‘listNode’ to ‘listNode*’ in assignment
temp->next = g->adj[y];
^

graph1.cpp:40:12: error: base operand of ‘->’ has non-pointer type ‘listNode’
g->adj[y]->next = temp;
^~

How can I fix them?

Source: Windows Questions C++

LEAVE A COMMENT