add_node
. x
is just a copy of current
, so new
changes the value of x but not the value of current. You can either make x a node**
(then there is no point in returning anything), or make add_node
return a node*
(then it won't need any parameters).#include<stdlib.h> #include<stdio.h> #include <iostream> using namespace std; struct node { char name[20]; node *nxt; // Pointer to next node }; node add_node (node * x) { cout << "Please enter the name of the person: "; cin >> x->name; x->nxt = NULL; return * x; } void print_lists(node * head){ while (head != NULL){ cout << head->name; head = head->nxt; } } int main() { node * head, * current; int i; head = NULL; i = 0; while (i < 5){ current = new node; * current = add_node(current); if (head == NULL){ head = current; } current = current->nxt; i = i + 1; } print_lists(head); return 0; } |
current = current->nxt;
current
to the value of current->nxt
( which is null ).current = new node;
current
to the address of a new node, but that doesn't affect current->nxt
.
|
|
current
always points to an existing node, and its value is not affected by new
.add_node
you already modify the node pointed by x, so there is no point to do so by returning something.