如何从指针获取数组的长度? [英] How to get the length of an array from a pointer?

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

问题描述

我无法找到指针数组的长度.假设我有:

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

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