c++linked-listcircular-list

Error while assigning the next element pointer in a circular linked list in a vector of struct instances


I want to create a circular linked list in a vector of struct instances. The vector is used because the count of the list elements is identified during execution of the process.

I have a problem while assigning the next pointer of the list elements.

The source:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

//element of circular linked list
struct Node {
    int data;
    Node* next;

    Node(int value) {
        data = value;
        next = nullptr;
    }
};

int main()
{
    vector<Node> peoples;

    peoples.push_back(Node(1));
    peoples.push_back(Node(2));

    peoples[0]->next = peoples[1];    

    return 0;
}

In the statement peoples[0]->next = peoples[1]; this error occurs:

C++ operator -> or ->* applies to "Node", not to, a pointer type


Solution

  • The members of peoples are Node objects, not Node* pointers. So, to access the next member, you need peoples[0].next.

    And, you need to use the & operator to get a Node object's address, like &peoples[1].


    (And later, when you do more push_backs, the vector might reallocate and make all the pointers invalid. Perhaps some other design is needed?).