Reputation: 16782
In a dynamically created array of structs, what does every entry of the struct get initialized to?
Details:
If we create a dynamic array of floats like so:
float* arr = ( float* ) malloc ( 100 * sizeof ( float ) );
then the array can be populated by anything (see here). But I am having trouble wrapping my head around what happens when we substitute structs in for floats like so
typedef struct
{
float x = 123.456;
} foo;
foo* arr = ( foo* ) malloc ( 100 * sizeof ( foo ) );
Are all the entries of the array arr
created with fully initialized foo
structs or do I have to go around and manually update the x
value?
Upvotes: 0
Views: 276
Reputation: 62439
The fact that the float
case can be "initialized" to anything should provide the answer you need - it's not in fact initialized, but it may contain anything, because no initialization is done. The same is true with a struct
- no initialization is done on allocation, so the (quite likely) garbage contents of the memory segment returned is what you'll get. If you care about the contents of your newly allocated memory (and you probably should), you need to initialize it explicitly yourself.
Upvotes: 1
Reputation: 98078
There is no difference between floats and structs. You need to manually initialize every dynamically allocated memory region.
Upvotes: 1
Reputation: 145899
typedef struct
{
float x = 123.456;
} foo;
You cannot have default values in structure types. This is not valid C code.
Objects allocated by malloc
have an indeterminate value.
Upvotes: 3