Trouble Setting up Doubly Linked List
Aug 15, 2011 at 1:42am UTC
I'm trying to use a class to set up a doubly linked list so that the pointers to the first and last nodes are returned correctly.
1 2
my_DLL("987" );
cout << my_DLL.get_first_char();
cout << my_DLL.first_char->data(); <---outputs 0!!!!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
class DLL
{
public :
DLL::DLL( const string &initial_string)
{
string my_input = init_value;
int this_digit;
D_Node<string> first_node((my_input[0] - 48), NULL, NULL);
D_Node<int > *head_ptr;
D_Node<int > *tail_ptr;
head_ptr = &first_node;
tail_ptr = &first_node;
for (size_t i = 1; i < my_input.length(); i++)
{
this_digit = my_input[i] - 48;
dlist_tail_insert(tail_ptr, this_digit);
}
first_char = head_ptr;
last_char = tail_ptr;
cout << first_char << endl;
cout << first_char->data() << endl; <---outputs '9'
}
private:
D_Node<int> *first_digit;
D_Node<int> *ones_digit;
};
The problem is that when all of this finishes, my two pointers don't work. They have the correct memory addresses stored in them, but when I try to use them, they return the wrong data. Can anybody see why this isn't working?
Thanks!
(p.s. sorry about the formatting in this post. Can't figure that out, either. Not my day, I guess.)
Last edited on Aug 15, 2011 at 1:50am UTC
Aug 15, 2011 at 1:54am UTC
You're creating your first_node on the stack. Nodes should be created in the heap.
Aug 15, 2011 at 2:19am UTC
The formatting issue is probably having three dashes --- in the code somewhere. I believe that splits it into an output window to the side.
Aug 15, 2011 at 2:26am UTC
Thanks. Not exactly sure how to do this. Here is my attempt, but it's not working:
D_Node<int > first_node((my_input[0] - 48), NULL, NULL);
1 2 3 4
first_node = new D_Node<int >;
first_node->set_data(my_input[0] - 48);
first_node->set_fore(NULL);
first_node->set_back(NULL);
My error is
first_node is not declared in this scope
Dynamic memory is still an Achilles heel for me. I thought that my new line 1 should create this variable. What am I missing?
Thanks.
@Zhuge - thanks for the three-dash information. I was using that to focus on where my issues were surfacing.
Aug 15, 2011 at 2:45am UTC
Never mind. I figured it out. I forgot to put a type in front of first_node.
Thanks a lot. I've spent tons of time on this, so it's good to have it figured out.
Topic archived. No new replies allowed.