Problem setting a pointer in a constructor

I have a constructor that creates a linked list from an input string. Each digit of the input string goes in its own node in the list. The constructor works fine, in that at the end of the constructor, I can iterate through the list and output the string.

However, I need to create a pointer to the first (and last) nodes in the newly created list, which I can also do. But when I get back to int main(), I can't get the pointer to function properly. I can prove (by cout) that my pointer has been created and the address stored in the pointer is the same at the end of the constructor as it is back in main(). But when I output the data stored in the node that the pointer points to, that data has changed.

Here' the relevant code:

1
2
3
4
5
6
7
8
9
10
11
int main ()
{
   string test_string = "987";
   Big_Int bi_1("987"); //tested

   //this outputs the same address that I see at the end of the contructor 
   cout << "bi_1 digit ptr: " << bi_1.get_first_digit_ptr() << endl;

   //but this outputs something that I don't recognize (it should output a 9
   cout << "bi_1 digit: " << bi_1.get_first_digit_ptr()->data() << endl;
}


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
32
33
34
35
36
37
38
39
	Big_Int::Big_Int( const string &init_value )
	{
	    string my_input = init_value;
            int this_digit;

        //read the string into doubly linked list

        //Create the first dnode
        D_Node<int> first_node((my_input[0] - 48), NULL, NULL);
        my_num_digits = 1;

        //create the head_ptr and tail_ptr
        D_Node<int> *head_ptr;
        D_Node<int> *tail_ptr;

        head_ptr = new D_Node<int>;
        tail_ptr = new D_Node<int>;

        //point the head and tail pointers
        head_ptr = &first_node;
        tail_ptr = &first_node;

        if (my_input.length() > 0)
        {
            for (size_t i = 1; i < my_input.length(); i++)
            {
                this_digit = my_input[i] - 48;
                dlist_tail_insert(tail_ptr, this_digit);
            }
        }

        first_digit = head_ptr;
        ones_digit = tail_ptr;

//output the linked list for testing - everything looks good
dlist_head_print_list(first_digit);
cout << "first_digit address: " << first_digit << endl;
cout << "first_digit data: " << first_digit->data() << endl << endl << endl;
	}


Note: first_digit and last_digit are private member variables like this:
<namespace>::D_Node<int> *first_digit;

Anyone see what I am doing wrong?

Thanks.
You are pointing to a local variable. When the constructor ends, the variable dies.
Also
1
2
3
4
5
6
        head_ptr = new D_Node<int>;
        tail_ptr = new D_Node<int>;

        //memory leak
        head_ptr = &first_node;
        tail_ptr = &first_node;
Topic archived. No new replies allowed.