使用指针获取数组的长度 [英] Get length of an Array using a pointer
问题描述
当我只知道一个指向数组的指针时,有没有办法获取数组的长度?
Is there a way to get the length of an Array when I only know a pointer pointing to the Array?
看下面的例子
int testInt[3];
testInt[0] = 0;
testInt[1] = 1;
testInt[2] = 1;
int* point;
point = testInt;
Serial.println(sizeof(testInt) / sizeof(int)); // returns 3
Serial.println(sizeof(point) / sizeof(int)); // returns 1
(这是来自 Arduino Code 的片段 - 对不起,我不会说"真正的 C).
(This is a snipplet from Arduino Code - I'm sorry, I don't "speak" real C).
推荐答案
简单的答案是不,你不能.您可能希望在内存中保留一个变量,用于存储数组中的项目数量.
The easy answer is no, you cannot. You'll probably want to keep a variable in memory which stores the amount of items in the array.
还有一个不太容易的答案.有一种方法可以确定数组的长度,但为此您必须用另一个元素标记数组的末尾,例如 -1
.然后循环遍历它并找到这个元素.这个元素的位置就是长度.但是,这不适用于您当前的代码.
And there's a not-so-easy answer. There's a way to determine the length of an array, but for that you would have to mark the end of the array with another element, such as -1
. Then just loop through it and find this element. The position of this element is the length. However, this won't work with your current code.
选择以上之一.
这篇关于使用指针获取数组的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!