1

Say I have a struct with an array inside it:

struct my_struct {
    // 128 will be enough for all of my use cases,
    // saves me from using malloc.
    double values[128]; 

    int value_count; 

    const char *info;
};

The C spec says about compound initializers:

6.5.2.5.14 102) For example, subobjects without explicit initializers are initialized to zero.

Meaning that if I zero initialize my struct, all of its 128 doubles will be initialized to zero. And if I explicitly initialize only the 3 first doubles, the remaining 125 doubles will be initialized to zero.

struct my_struct s = {
    // 3 values explicitly initialized,
    // the rest will be initialized to zero.
    .values = { 1.0, 2.0, 3.0 },

    .value_count = 3,

    .info = "sequence of reals",
};

I like the elegance of the designated initializer, but I don't like that I'm potentially wasting so much time clearing memory that I won't use. If I only care about the 3 first doubles, is there a way to make C not zero initialize the 125 remaining doubles? Should I avoid designated initializers if I don't want to waste cycles on memory clearing?

2
  • Change your struct to hold the first 3 values, and the a pointer to an array of the rest? Measure to make sure it's a real opposed to a perceived problem. Maybe the kernel initializes it for you (to avoid leaking info) so there no actual cost? Don't initialize but set the values you want? Commented Aug 15, 2022 at 0:25
  • 1
    Have you measured how much of the "so much time clearing memory" that you think you are wasting? Are you sure it's worth the time you're spending looking into how to avoid it? How much time do you imagine that this takes? Commented Aug 15, 2022 at 1:33

1 Answer 1

2

The C standard does not provide any feature to initialize some parts of an aggregate and not others in a definition. To give values to some parts and not others, simply assign the values separately:

struct my_struct s;
s.values[0] = 1.0;
s.values[1] = 2.0;
s.values[2] = 3.0;
s.value_count = 3;
s.info = "sequence of reals";

It is just source code; there is no magic between setting initial values in the definition and setting them in assignments—if there were some way to set some initial values in the definition without clearing all other parts of the structure, it would have the same effect as the above source code.

You can expect that some cycles will be expended clearing the 125 unused elements if the compiler cannot see that those elements are not used by subsequent code.

Sign up to request clarification or add additional context in comments.

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.