如果我只有指向第一个数组元素的指针,考虑到数组衰减,是否可以找到数组的长度?

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?

本文关键字:数组 是否 衰减 第一个 数组元素 考虑到 如果 指针      更新时间:2023-10-16

我正在创建一个整数数组,其输入将由用户给出,我将其传递给一个函数,在该函数中它衰减为指针(例如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而不是数组的众多原因之一。

向量实际上比数组更容易、更安全、更强大、更直观。您越早学习如何使用它们越好。