initialize linked list at compile time

Viewed 264

i have the following struct:

struct node {
    char *data;
    struct node *next;
};

I want to initialize it with some already known values.

E.g:

struct node {
    char *data;
    struct node *next;
} *root = &(struct node){"data1", &(struct node){"data2", NULL}};

It's possible to get the address of the struct that contains "data2"? or to assign root to the struct that contains "data2"?

Edit:

I want to make the following at compile time with compound literals:

struct node *b = &(struct node){"data2", NULL};
struct node *a = &(struct node){"data1", b};
a = b;

Edit2:

something like that:

struct node {
    char *data;
    struct node *next;
};
struct node *tmp, *root = &(struct node){"data1", tmp = &(struct node){"data2", root}};
root = tmp;

but i do not want tmp to exist at run time

2 Answers

I think you're looking for something like:

#include<stdio.h>

struct node { char *data; struct node *next; }
        b = {"data2", NULL}, a = {"data1", &b}, *root = &b;

int
main(void)
{
        printf("%s\n", root->data);
        return 0;
}

or perhaps:

struct node { char *data; struct node *next; };
struct node *a = &(struct node){"data1", &(struct node){"data2", NULL}} ;

int
main(void)
{
        struct node *b = a->next;
        return 0;
}

If you want to initialise two different pointers to the same object statically, you have to name that object and use its address. For example:

struct node {
    char *data;
    struct node *next;
};

char last_data[] = "last_data";
char* last_data_ptr = last_data;
struct node last_node = (struct node){last_data, NULL};
struct node* last_node_ptr = &last_node;
struct node* list = &(struct node){"first_data", &last_node};

Here &last_node is used twice, once to initialise last_node_ptr and once to initialize a field in an unnamed struct that is used to initialise list. Likewise, last_data is used twice, once for last_data_ptr and once for a field in last_node. You cannot do that with a literal. It can only initialise one variable.

Here's how once can build a circular linked list:

struct node
{
    char* data;
    struct node* next;
} list = {"one", &(struct node){"two", &(struct node){"three", &list}}};
struct node *root = &list;
Related