Access to variables in a union within a structure

Can someone explain why the first method of accessing the nested structural element inside the union in the structure works, and the second does not?

typedef struct element Node;
struct element
{
    int type;
    union
    {
        int value;
        Node *child[2];
    } u;
};
int main()
{
    Node n;
    Node *p;    
    n.type = 0;
    p = n.u.child[0];
    p->type = 10;  // 1st method
    (n.u.child[1])->type = 24;   // 2nd method
    return 0;
}
+3
source share
3 answers

Try the following:

int main()
{
    Node n;
    Node *p;    
    n.type = 0;

    // allocate memory for child nodes
    n.u.child[0] = (Node *)malloc(sizeof(Node));

    if (n.u.child[0] == NULL)
    {
        return 1;
    }

    n.u.child[1] = (Node *)malloc(sizeof(Node));

    if (n.u.child[1] == NULL)
    {
        free(n.u.child[0]);
        return 1;
    }

    p = n.u.child[0];
    p->type = 10;  // 1st method
    (n.u.child[1])->type = 24;   // 2nd method

    // release dynamically allocated memory
    free(n.u.child[0]);
    free(n.u.child[1]);

    return 0;
}

NOTE. Do not modify n.u.valueNode if you have already assigned its child [] pointers. You will overwrite one of the pointers and skip this memory, as well as crash, if after that you try to access the child [] array. Unions are complex - it’s best to avoid this kind of arrangement.

+2
source

, , , [0] [1]. ( , "1- " .)

+1

, union.

. . , , -, , , .

, à la C99:

Node n = { .type = 0 };

Node n = { 0 };

à la C89, . , 0, . .

+1

Source: https://habr.com/ru/post/1755104/


All Articles