如何从指针获取数组的长度? [英] How to get the length of an array from a pointer?
问题描述
我无法找到指针数组的长度.假设我有:
I'm having trouble finding the length of an pointer array. Let's say I have:
char array[40] = "hello"; // size 40
int length = sizeof array / sizeof array[0]; // no problem returns 40
//如何仅通过指向数组中第一个元素的指针来获取数组的长度?
//How do I get the length of the array with only a pointer to the first element in that array?
char* pchar = array;
//如果
std::strlen(pchar); // this returns the length of 5... i want length 40
//如果
int count = 0;
while(true)
{
if(*(pchar + count) == '\0') // returns 5...
break;
count++;
}
如何让它仅从指向数组中第一个元素的指针返回长度为 40?
我发现我可以做到这一点.
How do I get it to return length 40 just from a pointer to the first element in the array?
I found that I can do this.
int count = 0;
while(true)
{
if(*(pchar + count) == '\0' && *(pchar + count + 1) != '\0')
break;
count++;
}
这返回 39,这很好,但我觉得这在某些情况下可能会出错.
This returns 39, this is good but I feel like this can be buggy in some situations.
推荐答案
恐怕不行.您需要将数组的长度传递给需要它的任何人.或者您可以使用 std::array
或 std::vector
或类似的,它们会自行跟踪长度.
You can't, I'm afraid. You need to pass the length of the array to anyone who needs it. Or you can use a std::array
or std::vector
or similar, which keep track of the length themselves.
这篇关于如何从指针获取数组的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!