0

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;
}
3
  • I would just use a vector if you can. It'll make life much easier. Commented Jul 22, 2019 at 14:39
  • try A.next = new node*[2]; that would create an array of 2 pointers Commented Jul 22, 2019 at 14:39
  • 1
    If you don't use a vector, I believe that node**[2] is your problem since the array syntax implies that next is a pointer to the first node** element. (node***) Commented Jul 22, 2019 at 14:40

2 Answers 2

1

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*.

Sign up to request clarification or add additional context in comments.

2 Comments

@CompuChip But that changes the ownership semantics, and doesn't work in OP's case where they need multiple nodes to "join" into one.
Note that at least part of the overhead for std::vector<node*> is the size. If that is static, you could use std::array<node *, 2>, otherwise you'll need to record it somewhere
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.