[英]C++ arrays const char
Hello I have this very simple function: 您好,我有这个非常简单的功能:
void sample(int data[])
{
const int DataSize = data[sizeof(data)] // Last int in array contains data size
int DataTable[DataSize] = {}; // error here must have a constant value
}
How can i make an empty array table the size of my last int in array? 我怎样才能使空数组表的大小成为我数组中最后一个int的大小?
As Neil Kirk mentioned, raw array sizes must be compile-time constants. 正如Neil Kirk提到的那样,原始数组大小必须是编译时常量。
DataSize
is not a compile-time constant, it's a run-time constant. DataSize
不是编译时常量,而是运行时常量。
Use an std::vector
, its size can be determined at run-time. 使用
std::vector
,其大小可以在运行时确定。
Additionally, sizeof(data)
returns the size of data
in bytes , not the number of elements in it. 另外,
sizeof(data)
返回以字节为单位的data
大小,而不是其中的元素数。 You need to pass the size of data
as a parameter to be able to use it inside the function. 您需要将
data
大小作为参数传递,以便能够在函数内使用它。
void sample(int data[], int size)
{
const int DataSize = data[size - 1];
// size - 1 is the index of the last element in data.
std::vector<int> DataTable(DataSize);
// DataTable now contains DataSize ints, all initialized to 0.
}
Or, you could just turn data
into a vector too which would simplify things a lot: 或者,您也可以将
data
变成向量,这将大大简化事情:
void sample(const std::vector<int>& data) // Pass data as a const reference.
{
const int DataSize = data.back();
// The `back` function accesses the last element in a vector.
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.