pointers in struct

closed account (4ET0pfjN)
for a struct(structure data structure) that has a pointer member, why do we have to declare an instance of our struct as a pointer as in:
1
2
3
4
5
6
7
struct node
{
 int data;
 node *next;
}

node *newNode = new node;


shouldn't it just be: node newNode = new node and then if we wish to use the pointer member next, we do something like:
newNode->next = *anotherNode;

It sounds dumb question i'm not sure...
Last edited on
It's not clear to me what your question is exactly. But in order to declare a pointer, you need to use the asterisk. node newNode = new node is simply invalid.
1. The new operator returns a pointer to the newly created object. So you must store this pointer.

2. a struct that has pointer member is not a pointer in it self, so *anotherNode would not make much sense. do you mean &anotherNode

3. in doing this newNode->next = *anotherNode; your assigning a value to the member next, which is a pointer. Also -> only works with pointers so, newNode must be a pointer.

-blueberry
closed account (4ET0pfjN)
hi blueberry,

can you clarify a little when you say newNode->next = &anotherNode, why can't this be done? I was under impression a structure stores different data types and so a pointer is just another type that points to a nother struct...
newNode->next is a pointer to an object of type node; but node newNode (as in your example in your first post) is an object. If you are wanting to instantiate your object without using new, you just type node newNode. This syntax calls its constructor (if it has a default one.)
newNode->next = &anotherNode can be done, but what you typed in your example was newNode->next = *anotherNode;
Using your struct:

1
2
3
4
5
struct node
{
 int data;
 node *next;
}


You can create one on the stack:
1
2
//...
node stacknode;


See, you didn't have to create your object as a pointer, however, your pointer next must be initialized/assigned this way.

stacknode->next = new node;

or

stacknode->next = someothernodepointer;

or

stacknode->next = new node(someothernodeObject);

or

stacknode->next = &someothernodeObject;

In any case you might want to create default/copy constructors (and moves as well).

1
2
3
4
5
6
7
8
struct node
{
 int data;
 node *next;
   node(const node& rhs) : data(rhs.data), next(new node(*rhs->next)){}
   node() : data(0), next(0){}
   //etc...
}
closed account (4ET0pfjN)
That's a lot of options, clanmjc and i'm going to absorb it slowly, and I guess gist is the new operator returns a pointer as blueberry indicated so I must have left hand side be a pointer as in: node *newNode = new node;


Topic archived. No new replies allowed.