views:

94

answers:

2

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};
A: 

You can make head a pointer, but you'll need to initialize it in a function.

struct node head_node;
struct node *head = &head_node;

void
initialize() {
    *head = {10,&head_node,&head_node};
}

There's no way you can initialize head ptr directly in global scope.

Sudhanshu
+6  A: 

Solution 1:

#include <stdlib.h>
#include <stdio.h>


typedef struct node
{
  int data;
  struct node * after;
  struct node * before;
}node;
int main() {

    struct node* head = (struct node *)malloc(sizeof(struct node)); //allocate memory
    *head = (struct node){10,head,head}; //cast to struct node

    printf("%d", head->data);

}

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:

#include <stdlib.h>
#include <stdio.h>


typedef struct node
{
  int data;
  struct node * after;
  struct node * before;
}node;
int main() {

    struct node* head = &(struct node){10,head,head};

    printf("%d", head->data);

}

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.

Tyler
In other words I cannot allocate memory out in the global scope?
Y_Y