struct list_el
{
int val;
struct list_el * right, * left, *parent;
}item_default={0,NULL,NULL,NULL}; //Default values
This does not do what you think it does. You've basically written...
typename typedefinition variable = initial_value;
You've declared the type struct list_el
, defined it as { int val; struct list_el * right, * left, *parent; }
, declared a new variable of that type called item_default
, and assigned it the value {0,NULL,NULL,NULL}
.
Aside from the type definition, this is basically int foo = 0
.
We can test that by printing out the parts of item_default
.
int main(int argc, char const *argv[])
{
printf("%d\n", item_default.val);
printf("%p\n", item_default.right);
printf("%p\n", item_default.left);
printf("%p\n", item_default.parent);
return 0;
}
And these will be 0, 0x0 (ie. NULL
), 0x0, 0x0.
Unfortunately, C has no defaults for types. You always must initialize them. When working with structs, this typically means writing new
and destroy
functions so initialization and cleanup happens consistently.
// Declare the type and typedef in one go.
// I've changed the name from node to Node_t to avoid clashing
// with variable names.
typedef struct node
{
int val;
struct node *right, *left, *parent;
} Node_t;
// Any functions for working with the struct should be prefixed
// with the struct's name for clarity.
Node_t *Node_new() {
Node_t *node = malloc(sizeof(Node_t));
node->val = 0;
node->right = NULL;
node->left = NULL;
node->parent = NULL;
return node;
}
int main() {
Node_t *node = Node_new();
printf("%d\n", node->val);
printf("%p\n", node->right);
// and so on
return 0;
}
Note that I did not use calloc
. calloc
fills the memory with zeros, but the machine's representation of a null pointer is not necessarily zero. Using NULL
and 0
are safe, the compiler can do the translation from context, but calloc
doesn't know what you're going to do with the memory its zeroing. It's a relatively minor portability concern that's probably more of a problem these days for embedded systems.