如何可靠地获取 C 样式数组的大小? [英] How to reliably get size of C-style array?
问题描述
如何可靠地获取 C 样式数组的大小?经常推荐的方法似乎是使用sizeof
,但是在foo
函数中不起作用,其中传入x
:
How do I reliably get the size of a C-style array? The method often recommended seems to be to use sizeof
, but it doesn't work in the foo
function, where x
is passed in:
#include <iostream>
void foo(int x[]) {
std::cerr << (sizeof(x) / sizeof(int)); // 2
}
int main(){
int x[] = {1,2,3,4,5};
std::cerr << (sizeof(x) / sizeof(int)); // 5
foo(x);
return 0;
}
对这个问题的回答 推荐 sizeof
但他们并没有说如果你传递数组它(显然?)不起作用.那么,我必须使用哨兵吗?(我不认为我的 foo
函数的用户总是可以信任将哨兵放在最后.当然,我可以使用 std::vector
,但是那么我没有得到很好的速记语法 {1,2,3,4,5}
.)
Answers to this question recommend sizeof
but they don't say that it (apparently?) doesn't work if you pass the array around. So, do I have to use a sentinel instead? (I don't think the users of my foo
function can always be trusted to put a sentinel at the end. Of course, I could use std::vector
, but then I don't get the nice shorthand syntax {1,2,3,4,5}
.)
推荐答案
在 C 中,C 中的数组参数实际上只是指针,因此 sizeof()
不起作用.您要么需要将大小作为另一个参数传递,要么使用标记 - 以最适合您的设计为准.
In C array parameters in C are really just pointers so sizeof()
won't work. You either need to pass in the size as another parameter or use a sentinel - whichever is most appropriate for your design.
其他一些选项:
其他一些信息:
对于 C++,不是传递原始数组指针,您可能希望参数使用将数组包装在类模板中的东西,该模板跟踪数组大小并提供将数据复制到数组中的方法以安全的方式.类似于 STLSoft 的 array_proxy 模板 或
Boost 的 boost::array 可能会有所帮助.我以前使用过一个 array_proxy
模板,效果很好.在使用参数的函数内部,您可以获得类似std::vector
的操作,但函数的调用者可以使用简单的 C 数组.无需复制数组 -array_proxy
模板几乎自动负责打包数组指针和数组大小.
for C++, instead of passing a raw array pointer, you might want to have the parameter use something that wraps the array in a class template that keeps track of the array size and provides methods to copy data into the array in a safe manner. Something like STLSoft's array_proxy template or Boost's boost::array might help. I've used an
array_proxy
template to nice effect before. Inside the function using the parameter, you getstd::vector
like operations, but the caller of the function can be using a simple C array. There's no copying of the array - thearray_proxy
template takes care of packaging the array pointer and the array's size nearly automatically.
在 C 中用于确定数组中元素数量的宏(因为 sizeof() 可能会有所帮助 - 即,您不是在处理简单的指针):是否有标准返回数组长度的 C 函数?
a macro to use in C for determining the number of elements in an array (for when sizeof() might help - ie., you're not dealing with a simple pointer): Is there a standard function in C that would return the length of an array?
这篇关于如何可靠地获取 C 样式数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!