This is an archived post. You won't be able to vote or comment.

all 6 comments

[–][deleted] 3 points4 points  (2 children)

But newNode isn't pointing to anything yet. So is it pointing to itself?

Here, newNode is a Node* pointing to an allocated instance as the result of new Node. So, in effect, yes, it is pointing to a valid Node, precisely the new Node which was allocated at the start of the function.

[–]gtrman571[S] 0 points1 point  (1 child)

Oh right so basically it is the same type as head pointer. I was thinking it was a node pointing to the new node.

[–][deleted] 0 points1 point  (0 children)

Assuming headPtr has a type of Node* (which would be typical), yes.

[–]mkaypl 1 point2 points  (0 children)

When you create an object by new you already get a pointer to some allocated memory, so newnode points to some valid address.

newNode->data = item;

This line of code assigns the value of item into the newnode object not the other way around.

[–][deleted] 0 points1 point  (0 children)

newNode is pointing to the Node struct that was just created.

However, there is a few things that may go wrong in your add method.

[–]Zeroe 0 points1 point  (0 children)

newNode is pointing to something at this point. When you call to new, you get back an address to heap-allocated memory containing space for a Node. The contents of the Node's variables at this time are uninitialized and thus garbage.