Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing Malloc'ed structure

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};
like image 269
AndrewGrant Avatar asked Jul 15 '15 23:07

AndrewGrant


People also ask

How do you initialize a struct using malloc?

int black = 1; int white = 5; int **board; int i; int j; int k; for(i=0;i<xsize;i++) { for(j=0;j<ysize;j++) { if(i<(xsize/2) && j<(ysize/2) && (i+j)%2!=

Can malloc be used in a struct?

malloc allocates sizeof(struct node) bytes, and returns a void pointer to it, which we cast to struct node *. Under some conditions malloc could fail to allocate the required space, in which case it returns the special address NULL.

How to malloc struct array in C?

Create an Array of struct Using the malloc() Function in C The memory can be allocated using the malloc() function for an array of struct . This is called dynamic memory allocation. The malloc() (memory allocation) function is used to dynamically allocate a single block of memory with the specified size.


1 Answers

(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

like image 54
2 revs Avatar answered Sep 21 '22 11:09

2 revs