user420878
user420878

Reputation: 229

Pointers to Structure in C

What is the error in this code? Why i cant dereference the element the way I am trying it to.

#include<stdio.h>
typedef struct
{
    int value;
    struct node * left;
    struct node * right;
} node;

int main() {
    node* root,*temp;
    root = (node*) malloc(sizeof(node));
    root->value = 10;
    (root->left)= (node*) malloc(sizeof(node));
    (root->right)=(node*) malloc(sizeof(node));
    ((root->left)->value) =20;   // WHY AN ERROR HERE???
}   

Upvotes: 2

Views: 227

Answers (2)

jopasserat
jopasserat

Reputation: 5940

Your structure definition misses the typename that you reuse further. When you declare left and right field, the compiler does not know what struct node is. You need to declare that you structure is a node. This implies to change the typedef alias. See the correction hereafter, this compiles fine:

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
        int value;
        struct node * left;
        struct node * right;
} Node;

int main() {
        Node* root,*temp;
        root = (Node*) malloc(sizeof(Node));
        root->value = 10;
        (root->left)= (Node*) malloc(sizeof(Node));
        (root->right)=(Node*) malloc(sizeof(Node));
        ((root->left)->value) =20;   /* no more errors */

        return 0;
}

Upvotes: 11

phihag
phihag

Reputation: 288290

First of all, let me recommend to turn on all warnings. You'll see the first problem is with assigning root->left at all. You cannot reference the name established by typedef inside a struct definition. Instead, Use the struct name, like this:

typedef struct node_t {
    int value;
    struct node_t * left;
    struct node_t * right;
} node;

Upvotes: 3

Related Questions