Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 543
Leem.fin Avatar asked Sep 19 '16 09:09

Leem.fin


People also ask

Can you initialize struct values?

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".

How do you initialize a struct variable?

Structure members can be initialized using curly braces '{}'.

Can we initialize variable in structure in C?

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.

Can you initialize a struct to NULL?

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.


1 Answers

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.

like image 124
Lundin Avatar answered Sep 24 '22 02:09

Lundin