9

I am trying to initalize a structure using braces, but i am really trying to initalize the structure that is pointed to by a pointer returned from a malloc call.

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

foo bar = {5,6};

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

foo * bar = malloc(sizeof(foo));
*bar = {3,4};
1
  • 6
    *bar = (foo){ 3, 4};
    – BLUEPIXY
    Jul 15, 2015 at 23:32

2 Answers 2

9

(This was answered in comments, so making it a CW).

You need to cast the right-hand side of the assignment, like so:

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

As pointed out by @cremno in the comment, this isn't a cast but rather an assignment of a compound literal

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

A postfix expression that consists of a parenthesized type name followed by a brace enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list

3
  • 6
    It may look like a cast operator but it isn't one. The whole thing is a compound literal.
    – cremno
    Jul 15, 2015 at 23:37
  • @cremno So it would seem. Good point. I've updated the answer with a reference to the standard.
    – jpw
    Jul 15, 2015 at 23:41
  • As a notable bonus: any struct members you forgot to include in a compound literal initializer get zero-initialized by default (just like if they were static objects). See: stackoverflow.com/a/24936301/9959012
    – 6equj5
    Nov 25, 2022 at 19:11
1

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

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

2
  • I understand how to initialize it like that, I'm looking specifically for brace initialization. Jul 15, 2015 at 23:38
  • In that case, *bar = (foo) {3,4}; should word. demo Jul 15, 2015 at 23:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.