Mano Mini
Mano Mini

Reputation: 613

Initialize a struct in C using {}

In the marked line I get an error Error - expected expression

#include <stdlib.h>

struct list_head {
    struct list_head *next, *prev;
};

struct program_struct {
    const char *name;
    struct list_head node;
};
typedef struct program_struct program_t;

struct task_t {
    program_t blocked_list;
};

int main() {

    struct task_t *p = malloc(sizeof(*p));
    p->blocked_list.name = NULL;
    p->blocked_list.node = {&(p->blocked_list.node), &(p->blocked_list.node)}; //error

    return 0;
}

I know I can replace this line with

p->blocked_list.node.next = &(p->blocked_list.node);
p->blocked_list.node.prev = &(p->blocked_list.node);

But can I make it work using {} like I tried in the first piece of code?

Upvotes: 2

Views: 190

Answers (1)

P.P
P.P

Reputation: 121397

Initialization is allowed only when you define a variable. So, you can't use initializers in assignment. You can instead use C99's compound literals:

p->blocked_list.node = (struct list_head) {&(p->blocked_list.node), &(p->blocked_list.node)}; //error

Upvotes: 2

Related Questions