有没有办法内省数组的大小?

发布于 2024-09-02 08:27:18 字数 144 浏览 1 评论 0原文

在 C++ 中,给定一个这样的数组:

unsigned char bogus1[] = {
  0x2e, 0x2e, 0x2e, 0x2e
};

有没有办法内省 bogus1 来找出 is 是四个字符长?

In C++ given an array like this:

unsigned char bogus1[] = {
  0x2e, 0x2e, 0x2e, 0x2e
};

Is there a way to introspect bogus1 to find out is is four characters long?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

自演自醉 2024-09-09 08:27:18

当然:

#include <iostream>

int main()
{
  unsigned char bogus1[] = {
    0x2e, 0x2e, 0x2e, 0x2e
  };

  std::cout << sizeof(bogus1) << std::endl;

  return 0;
}

发出4。更一般地说,sizeof(thearray)/sizeof(thearray[0]) 是数组中的项目数。但是,这是一个编译时操作,只能在编译器知道“项目数量”的情况下使用(例如,不能在接收数组作为参数的函数中使用)。为了更通用,您可以使用 std::vector 代替裸数组。

Sure:

#include <iostream>

int main()
{
  unsigned char bogus1[] = {
    0x2e, 0x2e, 0x2e, 0x2e
  };

  std::cout << sizeof(bogus1) << std::endl;

  return 0;
}

emits 4. More generally, sizeof(thearray)/sizeof(thearray[0]) is the number of items in the array. However, this is a compile-time operation and can only be used where the compiler knows about that "number of items" (not, for example, in a function receiving the array as an argument). For more generality, you can use std::vector instead of a bare array.

孤者何惧 2024-09-09 08:27:18

使用 sizeof 需要注意的一件事是确保您不会意外地执行已衰减为指针的数组的 sizeof:

void bad(int a[10])
{
    cout << (sizeof(a) / sizeof(a[0])) << endl;
}

int main()
{
    int a[10];
    cout << (sizeof(a) / sizeof(a[0])) << endl;
    bad(a);
}

在我的 64 位机器上,此输出:

10
2

内计算的大小>bad 是不正确的,因为 a 将退化为指针。一般来说,不要信任作为函数参数传递的数组的 sizeof

One thing to be careful about with sizeof is making sure you don't accidentally do the sizeof an array that has decayed into a pointer:

void bad(int a[10])
{
    cout << (sizeof(a) / sizeof(a[0])) << endl;
}

int main()
{
    int a[10];
    cout << (sizeof(a) / sizeof(a[0])) << endl;
    bad(a);
}

On my 64 bit machine, this outputs:

10
2

The size computed inside bad is incorrect because a will have decayed to a pointer. In general, don't trust the sizeof an array that was passed as a function argument.

意中人 2024-09-09 08:27:18
int bogus1_size = sizeof(bogus1) / sizeof(unsigned char);
int bogus1_size = sizeof(bogus1) / sizeof(unsigned char);
天荒地未老 2024-09-09 08:27:18

这解决了指针衰减问题:

#include <cstddef>

template<typename T, std::size_t N>
std::size_t array_size(T(&)[N]) { return N; }

除非数组大小已知,否则它不会编译。

This gets around the pointer decay problem:

#include <cstddef>

template<typename T, std::size_t N>
std::size_t array_size(T(&)[N]) { return N; }

In that it will not compile unless the array size is known.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文