C Structs Nodes

c++struct

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(&times, '*', &n3, &n4, true);
setNode(&plus,  '+', &n2, &times, 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.

Best Solution

Given a Node_p which is a pointer to a struct Node_t, you can access members of the object using the arrow operator (->). So within the setNode() function, you can access left and right the same way you accessed value and set their values.

void setNode(Node_p np,
     int    value,
     Node_p left,
     Node_p right,
     bool   display) {

    np->value = value; /* sets the value field */
    np->left = left;   /* sets the left field */
    np->right = right; /* sets the right field */
    /* and so on... */
}

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 a Node_p as 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.,

void eval(Node_p np) {
    int value = np->value;    /* read the value field */
    Node_p left = np->left;   /* read the left field */
    Node_p right = np->right; /* read the right field */
}
Related Question