简体   繁体   English

如何从输入中定义的“外部” int定义结构中的数组大小

[英]How to define array size in a struct from an “external” int defined in input

I have a struct with an array in it. 我有一个带有数组的结构。 The size of this array needs to be 3*input_variable. 该数组的大小需要为3 * input_variable。 How can I define a number externally, which is multiplied by an input value, that I can use in a struct to declare the length of an array? 如何在外部定义一个数字乘以输入值,可以在结构中使用它来声明数组的长度?

I have tried defining the variable h outside of main as 我尝试将变量h定义为main外

extern h

then assigning it's value in main from the input variable. 然后通过输入变量在main中为其赋值。

I have also tried to use (in summary) 我也尝试使用(总结)

nt main(int argc, char** argv)
{
    int input_variable;
    std::cin << input_variable;

    int h = input_variable * 3;

    void some_function(); // function does some stuff
                          // with the structs

#ifndef ARRAY_SIZING
#define ARRAY_SIZING h
#endif

    return 0;
}

struct _struct_
{
    constexpr std::size_t b = ARRAY_SIZING;
    double* arr[b];
};

int some_function()
{
    // structs are used down here.

    return 0;
}

I would love to be able to allocate the size of an array in a struct using an input parameter. 我希望能够使用输入参数在结构中分配数组的大小。 Thank you. 谢谢。

Hm. 嗯。 Plain C-arrays in C++. C ++中的纯C数组。 Mostly never needed. 通常不需要。 OK, you want to interface to a library function. 好的,您想连接到库函数。

My guess is that the library does not expect an array, but a pointer. 我的猜测是该库不期望数组,而是指针。 And since your struct contains an array to pointer to doubles, I assume the lib wants to see a double**. 并且由于您的结构包含指向双精度指针的数组,因此我假设lib希望看到一个double **。

I hardly can imagine that old libraries use references or pointer to arrays, something like: 我几乎无法想象旧的库使用引用或指向数组的指针,例如:

void function (double* (&array)[10]); // Reference to array
void function (double* (*array)[10]); // Pointer to array

because also here you need an array with a size known at compile time. 因为在这里您还需要一个在编译时已知大小的数组。

I'd rather expect something like 我宁愿期待像

void function (double** array, size_t size); // Pointer to Pointer to double

So, use a std::vector like this: 因此,使用这样的std::vector

std::vector<double *> arr(input_variable * 3);

And if you want to hand over the arrays data to the lib functions, then use the vectors data function. 而且,如果要将数组数据移交给lib函数,请使用vectors data函数。

function (arr.data());

You could also create the array with new. 您也可以使用new创建数组。

Last hint: Do not use raw pointers. 最后提示:请勿使用原始指针。

I hope that I could help a little . 我希望我能有所帮助。 . .

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

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