C: Self-referencing struct

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • greenhorn2k12
    New Member
    • Mar 2012
    • 1

    C: Self-referencing struct

    I have a struct defined as follows:

    Code:
    typedef struct t_node
    	{
    	struct t_node* child;
    	struct t_node* parent;
    	} node;
    Supposedly the typedef name (in this case "node") can't be referenced in the struct itself, so the struct name (t_node) is used instead. But the idea is that the t_nodes child and parent will be addressed as "node" elsewhere, right?

    So I make the following:
    Code:
    1. node* root = (node*) malloc (sizeof (node));
    2. node* leaf = (node*) malloc (sizeof (node));
    3. n->parent = r;  // No complaints here
    4. r->children[i] = n;  // Compilation error C2679: binary '=' : no operator found which takes a right-hand operand of type 'node *' (or there is no acceptable conversion) ... while trying to match the argument list '(node, node *)'
    Why does line 3 work then, but not 4? And how would one resolve 4?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    First, children is not a member of t_node. Use child instead.

    Second, child[i] supposes an array. for an array, the name of the array is the address of element zero. You are assigning a t_node* as an array element. Therefore, child must the the address of a t_node* which make it a t_node**. But it's a t_node* instead. Hence the error.

    Comment

    Working...