Reputation: 2107
I'm making a stack in C++ to manage infix, postfix and prefix mathematical operations. I use 2 classes, one called Node (an auto referenced class) and other one called Stack. In Node I have 2 properties, one is ID (an int, only for tests) and element (is a char*). In Stack I manage all the nodes in 2 stacks, one stack manages the operands (stack1) and another stack manages the operators (stack2). If I use the expression: "53+72-30/38*912", the idea is that in the stack2 for example I should have [ *, /, -, +] and the ids for each object [4, 3, 2, 1], but the result for stack2 is as follows [ *, *, *, *] but the ids for each one are fine [4, 3, 2, 1]
I think the problem must be with the char*, but I don't know how to solve it, can you help me please?
Thanks in advance!
Stack.cpp
//this is inside of a loop that goes trough a char* (named expr)
char tmp[i] = expr[i];
char op[] = {tmp, '\0'}; //I do this because the constructor of Node requieres a char*,
//and it is because I use the class Node to manage the stack of operands, which are char*
//for example, '983' (I do not use int for this case, but I also may create a template...
//but I want to know how to make it with char*)
this->addOperatorToStack2(op);
Stack.cpp
//The method that adds an operator (a new node) to the stack
void Stack::addOperatorToStack2(char *op){
Node *tmpNode = new Node(op);
if(!currentNode){
currentNode = tmpNode;
}
else{
tmpNode->nextNode = currentNode;
currentNode= tmpNode;
}
}
Node.h
#ifndef NODE_H
#define NODE_H
class Node{
friend class Stack;
public:
Node(char *);
char* getElement() const;
private:
char *element;
Node *nextNode;
static int counter;
int id;
};
#endif
Node.cpp
#include "Node.h"
Node::Node(char *element){
this->nextNode = 0;
this->element = element;
counter++;
id = counter;
}
char* Node::getElement()const{
return this->element;
}
int Node::counter= 0;
Upvotes: 0
Views: 102
Reputation: 27470
Each Node shall own its element value:
class Node{
private:
char element[MAXSIZE];
};
And so your constructor Node::Node(const char *element)
shall make its own copy of the value - strncpy
or some as such.
Upvotes: 1