This probably is one of the easiest question ever in C programming language…
I have the following code:
typedef struct node
{
int data;
struct node * after;
struct node * before;
}node;
struct node head = {10,&head,&head};
Is there a way I can make head to be *head [make it a pointer] and still have the availability to use ‘{ }’ [{10,&head,&head}] to declare an instance of head and still leave it out in the global scope?
For example:
//not legal!!!
struct node *head = {10,&head,&head};
Solution 1:
Something as simple as
struct node *head = {10, head, head}is not going to work because you haven’t allocated the memory for the struct (the int and two pointers).Solution 2:
This will go out of scope – Solution 1 is superior for this reason and since you’re creating a linked list, I believe you need heap allocated memory – not stack allocated.