So, here’s the story. I’m trying to create a recursive descent parser that tokenizes a string and then creates a tree of nodes out of those tokens.
All of the pointers for my major classes are working… if you’re worked with an RDP before then you know what I’m talking about with program -> statement -> assignStmt… etc. The idea being that the program node has a child that points to the statement node, etc.
Here’s the problem. When I get to the end of the treenode I’m pointing to the actual tokens that the tokenizer created from the string.
So, let’s say the string is:
firstvar = 1;
In this case there are 4 tokens [{id} firstvar], [{assignment} =], [{number} 1], [{scolon}]
And I want my assignStmt node to point to the non-decorator portions of that statement.. namely, child1 of assignStmt would be [{id} firstvar] and child2 would be [{number} 1]…
HOWEVER. When I assign child1 to [{id} firstvar], and then move onward to the next tokens, the value of child1 changes as I move forward. So, if I change my global token to the next token ( in this case [{assignment} =] ) then child1 of the assignStmt changes with it.
Why is this? What can I do?! Thank you!
TOKEN* getNextToken(void);
//only shown here to you know the return... it's working properly elsewhere
typedef struct node {
TOKEN *data;
struct node *child1, *child2, *child3, *child4, *parent;
} node;
TOKEN *token;
Symbol sym;
struct node *root;
void getsym()
{
token = getNextToken();
sym = token->sym;
}
int main()
{
getsym();
//So, right now, from getsym() the global token has the value {identifier; firstvar}
struct node* tempNode;
tempNode = (struct node*) calloc(1, sizeof(struct node));
tempNode->child1 = tempNode->child2 = tempNode->child3 = tempNode->child4 = NULL;
tempNode->data = token;
getsym();
//BUT NOW from getsym() the global token has the value {assignment; =}, and
//subsequently the tempNode->data has changed from what it should be
//{identifier; firstvar} to what the global token's new value is: {assignment; =}
}
You are returning a pointer to a global variable, and that pointer will always be the same even if you modify the global variable.
The solution is to either allocate a new object each time, or to not use pointers at all and return the structure directly and let the compiler handle copying of the structures internal values.