C ++如何获得一个指针数组的长度? [英] c++ how to get the length of a pointer array?
问题描述
我无法找到一个指针数组的长度。比方说,我有:
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 ::阵列
或的std ::矢量
或类似的,它保持自身长度的轨道
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.
这篇关于C ++如何获得一个指针数组的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!