Malloc'ed structure initialization

I'm trying to initialize a structure using curly braces, but I'm actually trying to initialize the structure pointed to by the pointer returned from the call to malloc.

typedef struct foo{
    int x;
    int y;
} foo;

foo bar = {5,6};

      

I understand how to do this, but I need to do it in this context.

foo * bar = malloc(sizeof(foo));
*bar = {3,4};

      

+3


source to share


2 answers


(This was answered in the comments, so it became CW).

You need to specify the right side of the assignment, for example:

*bar = (foo) {3,4};

      



As @cremno pointed out in a comment, this is not a cast, but rather a complex literal assignment

The relevant section of the C99 standard is 6.5.2.5 Composite literals, which says:

A postfix expression consisting of a type name in parentheses and then a copied initializer list is a literal compound. It provides an unnamed object whose value is given by an initializer list

+5


source


bar is a pointer that contains a reference to the malloced foo struct



Use bar->x=3;bar->y=4

+1


source







All Articles