Leem.fin Leem.fin - 2 months ago 8
C Question

Initialize struct with one 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
My_TYPE*
& I only want to initialize one field there? E.g. I tried:

MY_TYPE *a = {.value = 123};


But I get compiler error
"Designator in intializer for scala type 'struct MY_TYPE *'"
.

Is it possible to initialize the struct with on field?

Answer

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.

Comments