1

I'm tasked with creating a program that turns something like ((X+3)*(X+4)) into a binary tree, along with some other features. So far, I have taken in the input, and parsed it into two stacks, one containing the operands, the other the operators.

I defined the stacks simply for now (so they only have a nextnode and char value. However, I seem to have problems adding values from the stacks into my tree (so probably a problem in defining the tree).

My stack is defined as such:

typedef struct node
{
    char value;
    struct node * nextnode;
} node;

My tree is defined:

typedef struct tree
{
    node * thisNode;
    struct tree *right, *left;
} tree;

I'm not sure about the node* part, perhaps it should be something different.

I've been considering the simple case of 2+3 for starters. In this case, the root of the tree should be +, with left being 2 and right being 3.

 +
/\
2 3

How to add something that's on a stack to my tree? I have tried using

root->thisNode = operatorTop;

Where operatorTop is the top of the operator stack (defined as node * operatorTop), but even that simple line seems to segfault.

2
  • You'll have to show us a complete program that segfaults. There's nothing inherently wrong with your data structures (other than that you're using a char for an int and you're typedefing named structs, which isn't exactly incorrect). Commented Nov 10, 2010 at 21:58
  • Thats pretty much all I was asking, is if there was something inherently wrong. I forget to label it, but this is homework, so I don't want /too/ much help. Hogan got me on the right track, it was exactly that. Commented Nov 10, 2010 at 22:01

1 Answer 1

4

Maybe the problem is you have not called malloc() to reserve the space for root.

(Compilers will report null pointer assignment, but segfault on null point dereference because you are pointing to a random place.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! that was it exactly. I knew it was something simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.