Reputation: 42592
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?
Upvotes: 10
Views: 2247
Reputation: 16213
You can use compound literals.
#include <stdio.h>
#include <stdbool.h>
struct MY_TYPE
{
bool flag;
short int value;
double stuff;
};
int main(void)
{
struct MY_TYPE *a = &(struct MY_TYPE){.value = 123};
printf("%d\n", a->value);
}
Upvotes: 5
Reputation: 213563
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.
Upvotes: 17
Reputation: 409166
It is possible, if you first create an actual instance of the structure initialized the way you want, and then make the pointer point to that.
E.g.
struct MY_TYPE a = {.value = 123};
struct MY_TYPE *p = &a;
If you want to allocate a structure dynamically, then no it is not possible. Then you need to do it in two steps: Allocation; Followed by initialization:
struct MY_TYPE *p = calloc(1, sizeof *p);
p->value = 123;
The error you get have nothing to do with the initialization, but that you try to initialize a pointer with something that is not a pointer.
Upvotes: 4