Sorry if this question has been asked before. On my search through SO I didn’t find one that asked what I wanted to know.
Basically, when I have this:
typedef struct node
{
int data;
node *node;
} *head;
and do node *newItem = new node;
I am under the impression that I am declaring and reserving space, but not defining, a pointer to struct node, is that correct?
So when I do
newItem->data = 100 and newItem->next = 0
I get confused. newItem = 0would declare what exactly? Both data and next? The object as a whole?
I’m especially confused when I use typedef. Which part is the macro? I assume node because that’s how I call it, but why do I need it?
Finally, what happens when I do:
node *temp;
temp = new node;
temp = head->next;
head->next = newItem;
newItem->next = temp;
I mean, head->next is a pointer pointing to object newItem, so I assume not to newItem.data or next themselves. So how can I use an uninitialized pointer that I described above safely like here? is head now not pointing to an uninitialized pointer?
No. You are declaring a pointer, allocating space on the stack for the pointer, and dynamically allocating storage for a node to it it.
Don’t confuse yourself by writing stuff like this:
The way to write the struct in C++ is:
You can now create a pointer:
which allocates storage for the pointer.
and you can dynamically allocate storage for a node, and make the pointer point to it:
or do it all in one:
Now when you say:
you are not allocating anything. You are assigning 10 to the member called
dataof the node instance pointed to bypnode. Of course, if you had given your node a constructor (which you should normally do), you could do it all in one: