Consider the following code:
struct Node { void* data; int ref; struct Node* next; }; typedef struct Node* NodePtr;
I found that I get segfaults whenever I try to do something with NodePtr fields. For instance:.
NodePtr node; node->ref = 1;
So, I have allocated some space for NodePtr, and now it works fine. Why is this? I assume that since node is just a pointer, it has no memory for its fields.
So, I tried to initialize NodePtr:
NodePtr node = { node->data = 0; node->next = NULL; node->ref = 0; };
And well, I got this error:
error: expected รข}รข before รข;รข token
This boils down to four questions:
- If my guess is wrong, why doesn't it work if I don't use malloc ()?
- Why is my initialization not working?
- Will initializing memory struct a sentence on the stack and solve my problem?
- If not, do I have an alternative to memory allocation for each structure I use?
source share