quick C++ question

Started by
7 comments, last by ontheheap 19 years, 6 months ago
I'm brushing up my C++, it's been a couple of years. I found this in a tutorial: struct node { int x; node *next; }; int main() { node *root; //This will be the unchanging first node root=new node; //Now root points to a node struct root->next=NULL; //The node root points to has its next pointer //set equal to NULL root->x=5; //By using the -> operator, you can modify the node return 0; //a struct (root in this case) points to. } My question is: on the line "root=new node;", why is it not root.next=new node? Thanks in advance
Advertisement
Well, root is a pointer to a node structure, so you wouldn't be able to use root.next like that (it would have to be (*root).next I believe, hence the -> operator.

root = new node is just creating a new head for a linked list. After that initial creation you can use root->next to add another node to the list.

Hope this helps.

-heap
That's becasue node is just a pointer, and memory has to be allocated to it before it's(i.e node's) 'next' memeber variable can hold an address.Makes sense?

Also -> operator is used for dynamically allocated objects unlike statically declared ones
______________________________________________________________________________________________________
[AirBash.com]
node is just a pointer? I think you mean root is just a pointer. which clears things up.

"node *root; //This will be the unchanging first node"

should have maybe read:

"node *root; //This will be a pointer to the first node"

Does this make sense?
ie, the line:

"node *root;"

creates a pointer to a node, not a node, right?
yea sorry about mixing up the names ;)

Yes what you said is correct.The var root points to the first chunk of memory.In this chunk there's space for another pointer to point to the next chunk of memory.Hence the name linked lists.
______________________________________________________________________________________________________
[AirBash.com]
Okay, great. I got it now. I think I was actually confused by his comment on the line:

node *root; //This will be the unchanging first node

Thanks!
Quote:Original post by braclayrab
ie, the line:

"node *root;"

creates a pointer to a node, not a node, right?


Exactly
______________________________________________________________________________________________________
[AirBash.com]
Correct. You are creating a pointer to a node with the line

node *root;

[nm]

This topic is closed to new replies.

Advertisement