I have a struct:
struct MY_TYPE {
boolean flag;
short int value;
double stuff;
};
I know I can intialize it by:
MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 };
But, now I need to create a pointer variable My_TYPE*
and I only want to initialize one field there? I tried e.g.:
MY_TYPE *a = {.value = 123};
But I get compiler error "Designator in intializer for scalar type 'struct MY_TYPE *'"
.
Is it possible to initialize the struct with one field?
An important thing to remember, at the moment you initialize even one object/ variable in the struct, all of its other variables will be initialized to default value. If you don't initialize the values in your struct, all variables will contain "garbage values".
Structure members can be initialized using curly braces '{}'.
To initialize a structure's data member, create a structure variable. This variable can access all the members of the structure and modify their values. Consider the following example which initializes a structure's members using the structure variables.
You can't. NULL is a pointer whose value is set to zero, but your mark and space properties are not pointer values. In your code as you have it, they will both be value types, allocated as part of your Pair struct.
First of all, you are mixing up struct MY_TYPE
and typedef. The code posted won't work for that reason. You'll have to do like this:
typedef struct
{
bool flag;
short int value;
double stuff;
} MY_TYPE;
You can then use a pointer to a compound literal, to achieve what you are looking for:
MY_TYPE* ptr = &(MY_TYPE){ .flag = true, .value = 123, .stuff = 0.456 };
But please note that the compound literal will have local scope. If you wish to use these data past the end of the local scope, then you have to use a pointer to a statically or dynamically allocated variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With