Pass by reference to pointers

closed account (4ET0pfjN)
As I understand, pass by reference to pointers is another way to pass arguments; it's supposed to be cleaner than pass by pointers to pointers (since compiler does the work behind the scenes), but curious as how would I get it to insert at front of this linked list e.g.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
struct node
{
	int data;
	node *next;
};

//using pass by ref to ptrs (i.e. cleaner version of pass by ptrs to ptrs) is ONLY available in C++
void insert_at_front(int data_, node *&front, node *&end)
{
	node *newNode = new node;
	node->data = data_;//NB: or you can use: (*node).data
	
	if ( front == NULL && end == NULL )
	{
		front = &node;
		end = &node;
		node->next = NULL;
	}
	else
	{
		node->next = front;
		front = &node; 
	}
}

int main()
{
  node *front = NULL; node *end = NULL;
  insert_at_front(88,front,end);//this doesn't work
  return 0;
}
Last edited on
from line 11 to line 22, the word 'node' (which is the type) should be replaced with the word 'newNode' (which is the name of the object).
closed account (4ET0pfjN)
Typo there. But is that the only issue?
Last edited on
Not the only issue of course.

newNode is already a pointer, so lines like "front = &newNode;" should be "front = newNode;"

NULL is undefined (you have no #includes)

there is a memory leak -- I recomment tracking node ownership, e.g. make each node own the rest of the list, then memory clean up becomes automatic.
Topic archived. No new replies allowed.