我如何获取数组的大小,以便我可以从函数声明所述数组

how can i get the size of an array so i can declare said array from a function

本文关键字:数组 我可以 函数 声明 何获取 获取      更新时间:2023-10-16
const int size = arraySize();
int list[size];

我收到以下错误:

表达式必须具有常量值

我知道这可能不是最好的方法,但它是为了一项任务。

您应该知道,在C++中没有动态分配的数组。

此外,const变量在编译时不一定是已知的!

您可以执行以下操作之一:

  1. 将函数arraySize声明为constexpr,假设您可以在编译时计算其值,或者创建一个常量(再次使用constexpr(来表示数组大小。
  2. 使用动态分配的对象,例如std::vector(这是一个可以扩展的"数组"(或指针。但是,请注意,当您使用指针时,您必须使用new来分配其内存,并使用容易出错的delete来释放。因此,我建议使用std::vector.

使用第一个,我们得到:

constexpr std::size_t get_array_size()
{
return 5;
}
int main()
{
constexpr std::size_t size = get_array_size();
int list[size];
}

完美编译。

另一件很高兴知道的事情是,有std::array可以为普通的恒定大小数组添加更多功能。

尝试动态分配此数组。

int size = arraySize();
int* list;
list = new int [size];

它应该有效。 此外,还有一个关于动态数组如何工作的精简解释:动态内存

请记住在不需要时释放动态分配的内存:

delete [] list;
相关文章: