I did an hour of googling trying to understand the usage of pointers in this code to no avail.
#include <cstddef>
using namespace std;
class Node {
public:
int data;
Node * next;
};
int main() {
Node * head = NULL;
Node * second = NULL;
Node * third = NULL;
head = new Node();
second = new Node();
third = new Node();
head->data = 1;
head->next = second;
second-> data = 2;
second-> next = third;
third-> data = 3;
third-> next = NULL;
}
I am confused about how these pointers are used.
Node * head = NULL;
Node * second = NULL;
Node * third = NULL;
head = new Node();
second = new Node();
third = new Node();
Why does the pointer point to the constructor of the class?Shouldn't it point to a memory address? What is this particular technique of using pointers called? Thank you in advance!
Ahh... These would be called "Node pointers", or "pointers to nodes." Their purpose is to point to
Nodes. ;)Snark aside, your understanding of pointers themselves seems okay: Pointers store the memory address of some piece of data.
In
head = new Node(), you've misunderstood how the new keyword and constructor interact:newallocates memory for a new object, calls the class constructor, and returns the address of the newly created instance. In this case, then,head = new Node()creates a brand newNodeobject in the memory, and returns the address - which is then saved into head`.It seems you might benefit from a good reference on C++, as a few comments have mentioned before. I can recommend Learn C++ if you aren't the type for books. You might find useful the introduction to pointers and the introduction to "dynamic memory allocation", which is all about
newand it's counterpartdelete.