I need the syntax correction for dynamic memory allocation of array of list in c++ using malloc its giving runtime error. The first dynamic memory allocation syntax works fine with new keyword but i need using malloc keyword, how can get that memory block with the malloc keyword as im getting with new keyword
#include<bits/stdc++.h>
using namespace std;
class Graph{
int nodes;
list<int> *l;
public:
Graph(int nodes)
{
this->nodes=nodes;
// l=new list<int>[nodes];
l=(list<int>*)malloc(sizeof(list<int>[nodes]));// syntax correction of this is needed
if(!l)
{
cout<<"memory not allocated";
}
}
void add_edge(int u,int v)
{
l[u].push_back(v);
l[v].push_back(u);
}
int size()
{
return sizeof(l);
}
void print_list()
{
for(int i=0;i<nodes;i++)
{
cout<<"adjacency nodes node "<<i<<" is : ";
for(auto ele:l[i])
{
cout<<ele<<" ";
}
cout<<endl;
}
}
};
int main()
{
int n;
cin>>n;
Graph graph=Graph(n);
for (int i = 0; i < n; i++)
{
int u,v;
cin>>u>>v;
graph.add_edge(u,v);
}
graph.print_list();
cout<<graph.size();
}