I was just assigned a project to do in C in my class, but my professor didn’t teach anything about C, so I’m just trying to learn as I go.
How do I assign values to different parts of a node?
The main code that runs I have is: (This was given in the assignment)
Node n2, n3, n4, times, plus;
setNode(&n2, 2, NULL, NULL, true);
setNode(&n3, 3, NULL, NULL, true);
setNode(&n4, 4, NULL, NULL, true);
printf("\n");
setNode(×, '*', &n3, &n4, true);
setNode(&plus, '+', &n2, ×, true);
printf(" Tree evaluation: %d\n\n", eval(&plus));
and in the header file:
typedef struct Node_t {
int value;
struct Node_t *left;
struct Node_t *right;
} Node, *Node_p;
What I have so far for setNode is:
void setNode(Node_p np,
int value,
Node_p left,
Node_p right,
bool display) {
np->value;
}
How do I fill in the values for left and right? And how do I access them in another method eval?
I’ve been googling for days and can’t figure out what I’m exactly looking for. I know Obj-C pretty well, but this is just over my head. Any answers or links to resources would be awesome.
Given a
Node_pwhich is a pointer to astruct Node_t, you can access members of the object using the arrow operator (->). So within thesetNode()function, you can accessleftandrightthe same way you accessedvalueand set their values.Note that the arrow operator can be used to access members if you have a pointer to any struct or union object in general.
Looking at how
eval()was used, it looks like it takes aNode_pas well. So to access the members, it’s done in exactly the same way also using the arrow operator except you’re probably reading values, not setting them.e.g.,