Thread: Confused results from Linked List

  1. #1
    Registered User dalek's Avatar
    Join Date
    May 2003
    Posts
    135

    Confused results from Linked List

    Please ignore any memory leaks here, I have removed the clean up code to reduce space.

    This is no doubt a very simple mistake, however I can't see it. If I use a pointer within the struct NODE to hold the integer data, The last number that I entered is all that is output.. however if I change the variable over to an auto variable the list works.
    Code:
    #include <iostream>
    
    using namespace std;
    
    typedef struct Node
    {
    	int *data;
    	Node *next;
    }NODE;
    
    // Function prototypes
    void insert(int *);
    void output(void);
    
    // The list
    NODE *list = NULL;
    
    int main(void)
    {
    	int num;
    
    	cout << "Enter a number: ";
    	cin >> num;
    
    	while (num != 999)
    	{
    		insert(&num);
    		cout << "Enter a number: ";
    		cin >> num;
    	}
    	output();
    
    	return 0;
    }
    
    void insert(int *data)
    {
    	NODE *temp = new NODE;
    	temp->data = new int;
    
    	temp->next = list;
    	temp->data = data;
    	list = temp;
    }
    
    void output(void)
    {
    	NODE *current;
    
    	current = list;
    
    	while (current != NULL)
    	{
    		cout << "Number: " << *current->data << endl;
    		current = current->next;
    	}
    }

  2. #2
    Open to suggestions Brighteyes's Avatar
    Join Date
    Mar 2003
    Posts
    204
    temp->data = data;

    becomes

    *temp->data = *data;

    Don't copy the pointers, copy the data that they point to.
    p.s. What the alphabet would look like without q and r.

  3. #3
    Registered User dalek's Avatar
    Join Date
    May 2003
    Posts
    135
    D'oh! Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Anyone good with linked list.....I am not....
    By chadsxe in forum C++ Programming
    Replies: 11
    Last Post: 11-10-2005, 02:48 PM
  2. Problem with linked list ADT and incomplete structure
    By prawntoast in forum C Programming
    Replies: 1
    Last Post: 04-30-2005, 01:29 AM
  3. problem with structures and linked list
    By Gkitty in forum C Programming
    Replies: 6
    Last Post: 12-12-2002, 06:40 PM
  4. How to use Linked List?
    By MKashlev in forum C++ Programming
    Replies: 4
    Last Post: 08-06-2002, 07:11 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM