0

I have a single instantiation of a struct called single_instance. This instance contains constants objects of type struct example_type.

typedef struct {
  int n;
} example_type;

struct {
  int some_variables;
  // ...
  const example_type t1;
  const example_type t2;
  // ...
} single_instance;

Let's say that I want to init single_instance.t1 to {1} and single_instance.t2 to {2}.

What is the most elegant way to do so?

Inline initialization is not possible:

struct {
  int some_variables;
  // ...
  const example_type t1 = {1};
  const example_type t2 = {2};
  // ...
} single_instance;

This doesn't work too:

struct {
  int some_variables;
  // ...
  const example_type t1;
  const example_type t2;
  // ...
} single_instance {0, {0}, {1}};

I have read multiple other threads related to this topic, however it seems that they all refer to initialize structs with "a name". In this case I want just one instantiation of single_instance, as such the type should not have a name.

1
  • 6
    The last one works. You just forgot the = Commented Jul 24, 2019 at 13:59

2 Answers 2

3

You can use designated initializers to explicitly initialize the members you are interested in. The remaining members will then be implicitly initialized to 0.

struct {
  int some_variables;
  // ...
  const example_type t1;
  const example_type t2;
  // ...
} single_instance = {.t1 = {1}, .t2 = {2}};
Sign up to request clarification or add additional context in comments.

Comments

1

This works for me (maybe You're just missing = in initialization):

#include<stdio.h>

typedef struct {
  int n;
} example_type;

struct {
  int some_variables;
  // ...
  const example_type t1;
  const example_type t2;
  // ...
} single_instance = {0, {1}, {2}};

int main() {

    printf("%d %d %d\n", single_instance.some_variables, single_instance.t1.n, single_instance.t2.n);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.