Pointer question

I have a struct for a linked list, if I declare it like this


1
2
3
4
5
6
struct node
	{
	const char *snake;
	node *tail;

	}*p;


am i right that p is now a pointer to a struct node?
What is the difference between this and just doing
node *p;
p = new node;

since I have to allocate the p pointer anyway?
I believe so. That should be the same as:

1
2
3
4
5
6
7
8
struct node
{
      const char *snake;
      node *tail;
};

node *p;
p = new node;


Oh, I misread that.
p = new node; is doing dynamic memory allocation but not experienced enough to say 100% if there is a difference between the two.
Last edited on by closed account z6A9GNh0
Really? I would have expected it to declare the pointer, but not fill it!
The difference is that in the first case your pointer does not initialized while in the second case a memory was allocated for an object of type node and its address was assigned to the pointer.
To make the first case to be similar the second case you can write

1
2
3
4
5
6
struct node
{
	const char *snake;
	node *tail;

} *p = new node;
Yeah, I had misread the question. I thought he was asking if doing
1
2
3
4
5
struct node
{
      const char *snake;
      node *tail;
}p; 

was the same as doing
1
2
3
4
5
6
7
8
9
 
struct node
{
      const char *snake;
      node *tail;
}

node *p; 
p = new node;  // thought his was just a example of allocating when I first read it 


Though, most tutorials and books I've read have said to refrain from doing
1
2
3
4
5
6
7
struct node
{
}*p, *jumper;

class Person
{
} *varches; 

Instead they say to do this
1
2
3
node *p;
node *jumper;
Person *varches;

Though they never really explain why this is a bad thing to do, but I just keep doing the method they recommended.
Last edited on by closed account z6A9GNh0
ok I think I understand now. So with the first pointer:

1
2
3
4
5
6
struct node
	{
	const char *snake;
	node *tail;

	}*p;


I can use *p to iterate through what is in the struct etc but I can't make it do things like adding a new node to the struct or assigning any new elements to the struct without dynamic allocation?

thanks for your answers guys
Topic archived. No new replies allowed.