Abhishek Kaushik
Abhishek Kaushik

Reputation: 57

How to create an array of pointers to structure using new?

I am trying to create a graph using linked list styled nodes where each node is a structure containing a key and an address to the next node, but I want to join multiple nodes to one node so I tried creating an array of pointers to structure and initialize them using new dynamically but it throws an error saying that it "cannot convert node*** to node** in assignment".

I have tried using struct node* next[] but it didn't work well. What am I missing here? Should I just use a vector of pointers instead of an array?

struct node
{
    int key;
    struct node** next;
};
int main()
{
    struct node A;
    A.key = 12;
    A.next = new node**[2];
    return 0;
}

Upvotes: 0

Views: 78

Answers (2)

eerorika
eerorika

Reputation: 238311

Should I just use a vector of pointers instead of an array?

This is often an ideal solution. This would fix the memory leak that your program has (or would have if it compiled in the first place). An example:

struct node
{
    int key;
    std::vector<node*> next;
};

// usage
A.next.resize(2);

Vector does have space overhead, which can be a problem with big graphs because the total overhead increases linearly in relation to number of nodes. If vector is not appropriate for you, an alternative is std::unique_ptr, which does not have any overhead compared to a bare pointer:

struct node
{
    int key;
    std::unique_ptr<node[]> next;
};

// usage
A.next.reset(new node*[2]);
new node**[2];

What am I missing here?

You're attempting to create an array of node** when you need an array of node*.

Upvotes: 1

gsamaras
gsamaras

Reputation: 73366

Should I just use a vector of pointers instead of an array?

YES!

After including the vector library, then in your structure, you would have a member like this:

std::vector<node*> next;

This is the C++ approach, using raw pointers is the C approach.

As an encyclopedian information though, with raw pointers, you would do:

A.next = new node*[2];

which means an array of two pointers.

Upvotes: 1

Related Questions