In place definition of dynamically allocated struct in C
If I were to define a statically allocated struct in place, I'd do: struct mystr开发者_运维百科ucture x = {3, 'a', 0.3}; Is there a way I can do the same in C but using malloc. Ofcourse, I could do a struct mystructure x = createNewMystruct(3, 'a', 0.3), (Where I'd define the createNewMyStruct function) but I would like to know if there is some other way possible.
Thanks.
Closest I can think of is this:
struct mystructure *p = malloc(sizeof(*p));
assert(p);
*p = (const struct mystructure){3, 'a', 0.3};
C99 only, so don't come crying to me if it doesn't work in MSVC.
You can define a temporary variable using the first approach, then malloc()
another struct and copy the temporary variable over that heap-allocated variable.
No, what you describe can not be done on the heap. (malloc) The closest is calloc() which will initialize all your allocated memory to zero.
I don't know why you would want to, but you can use the sizeof() function to determine how large any type is, and just malloc what you need. Referencing the correct 'variable' inside of this construct would be your own problem, of course! :-)
char* x = malloc(sizeof(int) + sizeof(char) + sizeof(float);
You can do like this with an anonymous block:
// Anonymous block
{
struct mystruct tmp = { ... };
realstruct = malloc ( sizeof ( struct mystruct ) );
if ( NULL == realstruct )
goto error;
*realstruct = tmp;
}
...also I think you can do something like this in C99...
// After allocation
*realstruct = (struct mystruct){ ... };
I would like to know if there is some other way possible.
Not in standard C, no.
精彩评论