如果我只有指向第一个数组元素的指针,考虑到数组衰减,是否可以找到数组的长度?
Is it possible to find the length of an array if I have only the pointer to the first array element taking into account Array Decay?
我正在创建一个整数数组,其输入将由用户给出,我将其传递给一个函数,在该函数中它衰减为指针(例如int * a),现在如何仅使用可用资源(即指向第一个数组元素的指针)获取函数中数组的长度?
我尝试过"模板"(模板),它适用于数组而不是指针。我不想使用"struct"(将数组放在结构中并将结构传递给功能),因为它只是避免了这个问题。我也不想将大小存储在数组中的一个块中,因为我不想消耗比所需内存更多的内存(即使它只是一个内存)。我也不想要迭代器("开始"和"结束"),它们大多不适用于指针。我也不想要 C++11 解决方案或 boost 库解决方案,因为我不想依赖版本或库。
#include <iostream>
using namespace std;
void func(int *a)
{
//Now entire programming is to be done here as array has been passed
//How to find length using pointer a only, so that I can proceed with
//array operations?
//This function is not aware of length because of Array Decay but
//atleast has a starting point that is the pointer.
}
int main()
{
int array[5]={2,3,4,5,6};
func(array);
//main()'s use is over now, control is shifted to void func(int *)
return 0;
}
我希望一个方法仅使用指针查找长度,也就是说,我希望在func()方法中以某种方式生成数字5(数组长度)。
不,这是不可能的。这是您通常应该使用std::vector
而不是数组的众多原因之一。
向量实际上比数组更容易、更安全、更强大、更直观。您越早学习如何使用它们越好。
相关文章:
- 如何找到大小'x'数组是否完全填充,在C++?
- 任意大小的 constexpr 数组是否可以用作 switch 语句中的案例?
- 在 constexpr 构造函数中初始化数组是否合法?
- 以这种方式初始化的 char 数组是否会自动添加空终止符?
- 检查反向数组是否与原始数组相同
- 如何检查二维字符数组是否有空字
- 检查数组是否等于的最快方法?
- 确定数组是否可以旋转 3 个连续的数组元素进行排序?
- 如何检查数组是否包含多个元素?
- 我在代码中收到一个运行时错误,该错误如何通过修改最多一个元素来查找数组是否可以变得不减少
- c ++ 如何断言 char 数组与否,检查 char 数组是否以 "0" 开头或包含"0"
- 下课时的数组是否可以正常工作?
- C++全局常量数组:是否保证合并(优化)到一个副本中
- 在 C++17 中声明大小为 0 的数组是否合法
- 如果在执行过程中替换二进制文件,"const"数组是否驻留在内存中?
- 临时数组是否可能
- 使用二维数组作为一维数组是否正确?可能会导致未定义的行为左右?
- 当有多个查询时,检查某些子数组是否排序的有效方法是什么?
- 用于检查 char 数组是否仅包含允许的字符的函数
- 检查数组是否'right' (C++)