Leem.fin Leem.fin - 1 year ago 89
C Question

Initialize struct with single field

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
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?

Answer Source

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;

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download