我如何获取数组的大小,以便我可以从函数声明所述数组
how can i get the size of an array so i can declare said array from a function
const int size = arraySize();
int list[size];
我收到以下错误:
表达式必须具有常量值
我知道这可能不是最好的方法,但它是为了一项任务。
您应该知道,在C++中没有动态分配的数组。
此外,const
变量在编译时不一定是已知的!
您可以执行以下操作之一:
- 将函数
arraySize
声明为constexpr
,假设您可以在编译时计算其值,或者创建一个常量(再次使用constexpr
(来表示数组大小。 - 使用动态分配的对象,例如
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;
相关文章:
- 在二维向量或数组中可以存储的最大元素数是多少?
- 任意大小的 constexpr 数组是否可以用作 switch 语句中的案例?
- 确定数组是否可以旋转 3 个连续的数组元素进行排序?
- C++指针/数组(我现在完全困惑,真的需要帮助)
- 我将 c++ 矢量数据集转换为 c 数组.我将相同的数据集传递到一个应该给出相同输出的函数中
- 我在代码中收到一个运行时错误,该错误如何通过修改最多一个元素来查找数组是否可以变得不减少
- 下课时的数组是否可以正常工作?
- 为什么该函数不会获得动态数组?(我正在使用指针和参考)
- 指针到数组何时可以转换为不同类型的指针到数组?
- 确定数组是否可以划分为两个子序列,每个子序列的顺序递增
- 无符号整数数组怎么可以包含负整数
- 对象数组作为链表中的字符数组 - 我对对齐的假设是否有效
- 带有初始化的c++新数组我以前从未在采访中见过
- 如何正确地将std::字符串转换为无符号char[]数组*.我觉得我做错了,有人给我指明了正确的方向
- 数组元素可以具有标识符
- 在c++中,整数数组之间可以有空元素吗?
- (C++)正在尝试打印char*数组(我认为)
- C++对象实例化数组(我正在尝试找到编译时解决方案)
- 如何测试使用 MPI 调用的 CC++ 代码:是否有任何一组我可以使用的模拟函数
- 实现一个 dinamic 数组(我可以访问不存在的位置)