Sign in to follow this  
braclayrab

quick C++ question

Recommended Posts

braclayrab    160
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

Share this post


Link to post
Share on other sites
ontheheap    798
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

Share this post


Link to post
Share on other sites
FireNet    187
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

Share this post


Link to post
Share on other sites
braclayrab    160
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?

Share this post


Link to post
Share on other sites
FireNet    187
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this