简体   繁体   中英

C++ - passing declared array as argument to struct

    float_t rotations[6] = {1.0f, 2.5f, 3.0f, 4.0f, 5.0f, 6.0f};
    fla_algo_config_t config_alt = {20.0f,
                                20.0f,
                                {1.0f, 2.5f, 3.0f, 4.0f, 5.0f, 6.0f},
                                mock_error_callback,
                                nullptr};

    fla_algo_config_t config = {20.0f,
                                20.0f,
                                rotations,
                                mock_error_callback,
                                nullptr};

config_alt works. However, it is cumbersome to write out the entire array each time I would like to pass it to the struct. I would like to just pass the rotations array directly, so it doesn't need to be rewritten.

However, I get the following error:

error: array must be initialized with a brace-enclosed initializer nullptr};

I am guessing it wants me to enclose rotations with braces. However, if I do this, now I am passing an array of arrays, but fla_algo_config_t expects an array.

How can I pass the array? I have tried passing *rotations, but this only passes the first value.

How about

#define ROTATIONS {1.0f, 2.5f, 3.0f, 4.0f, 5.0f, 6.0f}
fla_algo_config_t config_alt = {20.0f,
                                20.0f,
                                ROTATIONS,
                                mock_error_callback,
                                nullptr};

If you still need rotations[] , you can still do

float_t rotations[6] = ROTATIONS;

If you want to use an initialization list, you have to use curly braces. See eg here . Therefore, you cannot just pass rotations , because it's not an initialization list, but an array.

Another option if you don't like the #define :

void initFlaAlgoConfig(fla_algo_config_t& config, float_t (&rotations)[6]) // FYI: The 6 should not be hard coded ;)
{
  // or use memcpy()
  for(int i = 0; i < 6; ++i)
  {
    config.thirdMember[i] = rotations[i];
  }
}

Then it could work like this:

float_t rotations[6] = {1.0f, 2.5f, 3.0f, 4.0f, 5.0f, 6.0f};
fla_algo_config_t config = {20.0f,
                            20.0f,
                            {0}, // default, will be overwritten in initFlaAlgoConfig()
                            mock_error_callback,
                            nullptr};
initFlaAlgoConfig(config, rotations);

However, this will cost you runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM