I have this structure definition:
typedef struct node_bst
{
int data;
struct node_bst *lchild;
struct node_bst *rchild;
struct node_bst *parent;
} node_bst;
I tried to create a pointer to the structure using this:
node_bst *root;
and allocated memory to it like this:
root= malloc(sizeof(node_bst));
Now, in order to initialize the data items in it I was tried this statement (taking a cue from the usual initialization of structure variables):
*root= {0, NULL, NULL, NULL};
But the compiler threw off an error
error: expected expression before ‘{’ token
I looked it up and found that I need to typecast it like this:
*root= (node_bst) {0, NULL, NULL, NULL};
Now it works fine but my question is, why do i need to do this?
I expected that the compiler would already know that root is a pointer to node_bst type structure variable. So why the need to typecast the rvalue?
Another strange thing:
int *a= malloc(sizeof(int));
*a= 4;
This works just fine.
node_bst root; root = {0, NULL, NULL, NULL};
. – Acromion*a = 4;
, you don't need a "cast" since the constant of type integer is just a number. – Towrey(node_bst) {0, NULL, NULL, NULL}
is a single entity and not a cast followed by a struct. – Towreyconst
. – Auspex(node_bst)
anyways why do i need it? I meannode_bst root= {0, NULL, NULL, NULL};
works as i expected. Why? – Whited(node_bst)
by itself is nothing. It is the(node_bst)
along with the{ ... }
that makes up a compound literal. – Towreyconst
? – Towrey*root
. Note that compound literals are not constants! In fact evenstatic const
does not make a constant, but even not-so-good compilers should handle it that way. and it will help detect problems if e.g. the*
on the lhs of the assignment is forgotten. Always head for safe code and support your compiler. – Auspex