如何可靠地获得C风格的数组的大小? [英] How to reliably get size of C-style array?
问题描述
我如何可靠地得到一个C数组的大小?经常推荐的方法似乎是使用的sizeof
,但它并没有在富
函数,其中正常工作 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;
}
解答<一个href=\"http://stackoverflow.com/questions/1969588/looping-a-fixed-size-array-without-defining-its-size-in-c\">this问题建议的sizeof
,但他们不说,它(显然?)不会,如果你通过围绕阵列工作。所以,我必须用一个哨兵呢? (我不认为我的富
功能的用户总是可以信任的把一个哨兵在最后。当然,我可以使用 STD ::矢量
,但我没有得到漂亮的语法速记 {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's提高::数组可能的帮助。我以前用过的
array_proxy
模板不错的效果。使用参数的函数内部,你会得到的std ::矢量
一样操作,但该函数的调用者可以使用一个简单的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()可能会帮助 - 也就是说,你不是一个简单的指针处理):<一href=\"http://stackoverflow.com/questions/1598773/is-there-a-standard-function-in-c-that-would-return-the-length-of-an-array/1598827#1598827\">http://stackoverflow.com/questions/1598773/is-there-a-standard-function-in-c-that-would-return-the-length-of-an-array/1598827#1598827
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): http://stackoverflow.com/questions/1598773/is-there-a-standard-function-in-c-that-would-return-the-length-of-an-array/1598827#1598827
这篇关于如何可靠地获得C风格的数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!