简体   繁体   English

C ++ - 将声明的数组作为参数传递给struct

[英]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. config_alt有效。 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. 我想直接传递rotations数组,因此不需要重写。

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. 但是,如果我这样做,现在我传递一个数组数组,但fla_algo_config_t需要一个数组。

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 如果你还需要rotations[] ,你仍然可以

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. 因此,您不能只传递rotations ,因为它不是初始化列表,而是数组。

Another option if you don't like the #define : 如果你不喜欢#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. 但是,这将花费您的运行时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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