Search code examples
ctreestack

Can't assign a tree node into a stack


typedef struct tree_node{
    int table_node[4][4];
    struct tree_node* parent;
    struct tree_node* children[4];
}tree_node;

struct tree_node* new_Node(int **field, tree_node* parent){
    tree_node* newNode = (tree_node*)malloc(sizeof(tree_node));

    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            newNode->table_node[i][j] = field[i][j];
        }
    }

    newNode->parent = parent;
    
    for(int i = 0; i < 4;i++) {
        newNode->children[i] = NULL;
    }
    return newNode;
    
}

typedef struct Stack{
    int top;
    int capacity;
    tree_node* nodes;
}Stack;

struct Stack* new_Stack(){
    struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
    stack->capacity = 1000;
    stack->top = -1;
    stack->nodes = (tree_node*)malloc(stack->capacity * sizeof(tree_node));
}

I created a tree and a stack to hold them but i get an error message in the push function below:

void push(struct Stack* stack, tree_node* node){
    if(is_Full(stack))
        return;
    stack->nodes[++stack->top] = node;
}

The message reads:"a value of type "tree_node *" cannot be assigned to an entity of type "tree_node"", and its shown as an error at the equal sign in line: stack->nodes[++stack->top] = node;

How do i fix this, and what causes this?


Solution

  • stack->nodes = (tree_node*)malloc(stack->capacity * sizeof(tree_node)); creates an array of tree nodes. `

    stack->nodes[++stack->top] is then a tree node, not a tree node pointer.

    in void push(struct Stack* stack, tree_node* node), you can see that node is actually a pointer to a node.

    either change the stack->nodes into an array of pointers, so that you can free the pointers directly with the stack struct.

    or you could dereference the node in push with stack->nodes[++stack->top] = *node but remember, how will you free the memory from the original node, seeing as the stack is a copy.

    It seems as you would want to change the stack into an array of struct pointers.

    Hope this helps :)