有没有办法内省数组的大小?
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当然:
发出
4
。更一般地说,sizeof(thearray)/sizeof(thearray[0])
是数组中的项目数。但是,这是一个编译时操作,只能在编译器知道“项目数量”的情况下使用(例如,不能在接收数组作为参数的函数中使用)。为了更通用,您可以使用 std::vector 代替裸数组。Sure:
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 usestd::vector
instead of a bare array.使用
sizeof
需要注意的一件事是确保您不会意外地执行已衰减为指针的数组的 sizeof:在我的 64 位机器上,此输出:
在
内计算的大小>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:On my 64 bit machine, this outputs:
The size computed inside
bad
is incorrect becausea
will have decayed to a pointer. In general, don't trust thesizeof
an array that was passed as a function argument.这解决了指针衰减问题:
除非数组大小已知,否则它不会编译。
This gets around the pointer decay problem:
In that it will not compile unless the array size is known.