There's something wrong with my push function, or how I'm initializing the linked list. Can anyone tell why?

The pointer 'operands' wont point to the new head, and always points to the first node created. Adding a second node appears to partially work, (second node->next points to the first node, first node->prev points to the second node). But after exiting the push function, 'operands' still points to the first node, which is now the last node...

NodeOperand* operands = new NodeOperand; // Linked list for operands
InitOperand(operands); // Initialize operands

pushDigit('4', operands); // works fine
pushDigit('2', operands); // adds second node, to the front of existing node, but operands still points to the node 4, and not the new head
pushDigit('9', operands); // Seems to basically replace the node 2, with operands still pointing to node 4
void InitOperand(NodeOperand* operand)
{
	// Desc
	cout << "Init... ";
	//operand = new NodeOperand;
	operand->data = 0;
	operand->next = operand;
	operand->prev = operand;
	
	cout << "done" << endl;
}
void pushDigit(char digit, NodeOperand* operands)
{
	if(isemptyOperands(operands))
	{
		operands->data = int(digit-48);
		operands->next = 0;
		operands->prev = 0;
	}
	else
	{
		/*NodeOperand* newNode = new NodeOperand;
		newNode->data = int(digit-48);
		newNode->next = operands;
		newNode->prev = 0;
		operands->prev = newNode;
		operands = newNode;*/
		NodeOperand* temp = operands;
		operands = new NodeOperand;
		operands->next = temp;
		temp->prev = operands;
		operands->prev = 0;
		operands->data = int(digit-48);

	}
	return;
}

Recommended Answers

All 2 Replies

Here's an example that shows your most immediate problem:

#include <cstring>
#include <iostream>

void foo ( char *p )
{
  p = new char[4];
  std::strcpy ( p, "foo" );
}

void bar ( char **p )
{
  *p = new char[4];
  std::strcpy ( *p, "bar" );
}

void baz ( char*& p )
{
  p = new char[4];
  std::strcpy ( p, "baz" );
}

int main()
{
  char *p = 0;

  foo ( p );
  std::cout<<"p == "<< ( p != 0 ? p : "(null)" ) <<'\n';
  delete p;

  bar ( &p );
  std::cout<<"p == "<< ( p != 0 ? p : "(null)" ) <<'\n';
  delete p;

  baz ( p );
  std::cout<<"p == "<< ( p != 0 ? p : "(null)" ) <<'\n';
  delete p;
}

foo is equivalent to what you're doing now. bar and baz are two ways to fix the problem. The problem is that pointers are passed by value, so when foo assigns to p, it's actually modifying the copy rather than the original. Passing a pointer to the pointer or a reference to the pointer allows the function to access the original pointer.

Fix that and we can talk about any further problems.

You are a champ, thanks so much!

Now I just need to fix my logic and I'll be home free. Thanks again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.