使用指针获取数组长度 [英] Get length of an Array using a pointer

查看:500
本文介绍了使用指针获取数组长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法得到一个数组的长度时,我只知道一个指针指向数组?

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一snipplet - 对不起,我不说话真正的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 。然后,只需通过它循环,找到这个元素。此元素的位置的长度。但是,这不会与当前的code工作。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆