C++ 如何找到 int[] 的大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2037736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:55:00  来源:igfitidea点击:

How to find the size of an int[]?

c++arrays

提问by adam

I have

我有

int list[] = {1, 2, 3};

How to I get the size of list?

我如何获得的大小list

I know that for a char array, we can use strlen(array)to find the size, or check with '\0'at the end of the array.

我知道对于 char 数组,我们可以使用strlen(array)来查找大小,或者'\0'在数组末尾检查。



I tried sizeof(array) / sizeof(array[0])as some answers said, but it only works in main? For example:

我尝试sizeof(array) / sizeof(array[0])了一些答案,但它只适用于主要?例如:

int size(int arr1[]){
    return sizeof(arr1) / sizeof(arr1[0]);
}

int main() {
    int list[] = {1, 2, 3};

    int size1 = sizeof(list) / sizeof(list[0]); // ok
    int size2 = size(list_1); // no
    // size1 and size2 are not the same
}

Why?

为什么?

回答by Prasoon Saurav

Try this:

尝试这个:

sizeof(list) / sizeof(list[0]);

Because this question is tagged C++, it is always recommended to use std::vectorin C++ rather than using conventional C-style arrays.

因为这个问题被标记为 C++,所以总是建议std::vector在 C++ 中使用而不是使用常规的 C 样式数组。



An array-typeis implicitly converted into a pointer-typewhen you pass it to a function. Have a look at this.

当您将An传递给函数时,它array-type会隐式转换为 a pointer-type。看看 这个。

In order to correctly print the sizeof an array inside any function, pass the array by reference to that function (but you need to know the size of that array in advance).

为了在任何函数内正确打印数组的大小,请通过对该函数的引用传递数组(但您需要提前知道该数组的大小)。

You would do it like so for the general case

对于一般情况,你会这样做

template<typename T,int N> 
//template argument deduction
int size(T (&arr1)[N]) //Passing the array by reference 
{
   return sizeof(arr1)/sizeof(arr1[0]); //Correctly returns the size of 'list'
   // or
   return N; //Correctly returns the size too [cool trick ;-)]
}

回答by Carl Smotricz

The "standard" C way to do this is

执行此操作的“标准”C 方法是

sizeof(list) / sizeof(list[0])

回答by avakar

You could use boost::size, which is basically defined this way:

您可以使用boost::size,它基本上是这样定义的:

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

Note that if you want to use the size as a constant expression, you'll either have to use the sizeof a / sizeof a[0]idiom or wait for the next version of the C++ standard.

请注意,如果要将大小用作常量表达式,则必须使用sizeof a / sizeof a[0]习惯用法或等待 C++ 标准的下一个版本。

回答by Mehrdad Afshari

You can'tdo that for a dynamically allocated array (or a pointer). For static arrays, you can use sizeof(array)to get the whole array size in bytes and divide it by the size of each element:

对于动态分配的数组(或指针),您不能这样做。对于静态数组,您可以使用sizeof(array)以字节为单位获取整个数组大小并将其除以每个元素的大小:

#define COUNTOF(x) (sizeof(x)/sizeof(*x))

To get the size of a dynamic array, you have to keep track of it manually and pass it around with it, or terminate it with a sentinel value (like '\0' in null terminated strings).

要获取动态数组的大小,您必须手动跟踪它并将其传递给它,或者使用标记值终止它(如空终止字符串中的 '\0' )。

Update:I realized that your question is tagged C++ and not C. You should definitely consider using std::vectorinstead of arrays in C++ if you want to pass things around:

更新:我意识到你的问题被标记为 C++ 而不是 C。std::vector如果你想传递一些东西,你绝对应该考虑在 C++ 中使用而不是数组:

std::vector<int> v;
v.push_back(1);
v.push_back(2);
std::cout << v.size() << std::endl; // prints 2

回答by Jerry Coffin

Since you've marked this as C++, it's worth mentioning that there is a somewhat better way than the C-style macro:

由于您已将其标记为 C++,因此值得一提的是,有一种比 C 样式宏更好的方法:

template <class T, size_t N>
size_t countof(const T &array[N]) { return N; }

This has the advantage that if you accidentally try to pass something other than an array to it, the code simply won't compile (whereas passing a pointer to the C macro will compile but produce a bad result. The disadvantage is that this doesn't give you a compile-time constant, so you can't do something like this:

这样做的好处是,如果您不小心尝试将数组以外的内容传递给它,则代码根本不会编译(而将指针传递给 C 宏会编译但会产生错误的结果。缺点是这不会) t 给你一个编译时常量,所以你不能做这样的事情:

int a[20];

char x[countof(a)];

In C++11 or newer, you can add constexprto get a compile-time constant:

在 C++11 或更高版本中,您可以添加constexpr以获得编译时常量:

template <class T, size_t N>
constexpr size_t countof(const T &array[N]) { return N; }

If you really want to support the same on older compilers, there is a way, originally invented by Ivan Johnson, AFAIK:

如果您真的想在较​​旧的编译器上支持相同的功能,那么有一种方法,最初由 AFAIK 的 Ivan Johnson 发明:

#define COUNTOF(x)  (                                           \
  0 * sizeof( reinterpret_cast<const ::Bad_arg_to_COUNTOF*>(x) ) +  \
  0 * sizeof( ::Bad_arg_to_COUNTOF::check_type((x), &(x))      ) +  \
  sizeof(x) / sizeof((x)[0])  )                                  


class Bad_arg_to_COUNTOF
{
public:
   class Is_pointer;
   class Is_array {};  
   template<typename T>
   static Is_pointer check_type(const T*, const T* const*);
   static Is_array check_type(const void*, const void*);
};

This uses sizeof(x)/sizeof(x[0]) to compute the size, just like the C macro does, so it gives a compile-time constant. The difference is that it first uses some template magic to cause a compile error if what you've passed isn't the name of an array. It does that by overloading check_type to return an incomplete type for a pointer, but a complete type for an array. Then (the really tricky part) it doesn't actually call that function at all -- it just takes the size of the type the function would return, which is zero for the overload that returns the complete type, but not allowed (forcing a compile error) for the incomplete type.

这使用 sizeof(x)/sizeof(x[0]) 来计算大小,就像 C 宏一样,所以它给出了一个编译时常量。不同之处在于,如果您传递的不是数组的名称,它首先使用一些模板魔术来导致编译错误。它通过重载 check_type 来为指针返回不完整的类型,但为数组返回完整的类型。然后(真正棘手的部分)它实际上根本没有调用该函数——它只需要函数将返回的类型的大小,对于返回完整类型的重载来说为零,但不允许(强制编译错误)对于不完整的类型。

IMO, that's a pretty cool example of template meta programming -- though in all honesty, the result is kind of pointless. You really only need that size as a compile time constant if you're using arrays, which you should normally avoid in any case. Using std::vector, it's fine to supply the size at run-time (and resize the vector when/if needed).

IMO,这是模板元编程的一个非常酷的例子——尽管老实说,结果有点毫无意义。如果您使用数组,您实际上只需要该大小作为编译时常量,通常在任何情况下都应该避免使用数组。使用std::vector,可以在运行时提供大小(并在需要时/如果需要调整向量的大小)。

回答by Dirk Eddelbuettel

Besides Carl's answer, the "standard" C++ way is not to use a C intarray, but rather something like a C++ STL std::vector<int> listwhich you can query for list.size().

除了 Carl 的回答,“标准”C++ 方法不是使用 Cint数组,而是使用 C++ STL 之类的东西std::vector<int> list,您可以查询list.size().

回答by coming out of void

when u pass any array to some function. u are just passing it's starting address, so for it to work u have to pass it size also for it to work properly. it's the same reason why we pass argc with argv[] in command line arguement.

当你将任何数组传递给某个函数时。您只是传递它的起始地址,因此要使其正常工作,您还必须传递它的大小才能正常工作。这与我们在命令行争论中使用 argv[] 传递 argc 的原因相同。

回答by Nooruddin Dar

You can make a template function, and pass the array by reference to achieve this.

您可以制作一个模板函数,并通过引用传递数组来实现这一点。

Here is my code snippet

这是我的代码片段

template <typename TypeOfData>


void PrintArray(TypeOfData &arrayOfType);

int main()

{

    char charArray[] = "my name is";

    int intArray[] = { 1,2,3,4,5,6 };

    double doubleArray[] = { 1.1,2.2,3.3 };


    PrintArray(charArray);

    PrintArray(intArray);

    PrintArray(doubleArray);

}


template <typename TypeOfData>

void PrintArray(TypeOfData &arrayOfType)

{

    int elementsCount = sizeof(arrayOfType) / sizeof(arrayOfType[0]);


    for (int i = 0; i < elementsCount; i++)

    {

        cout << "Value in elements at position " << i + 1 << " is " << arrayOfType[i] << endl;

    }

}

回答by Rodrigo Santos

If you want to know how much numbers the array have, you want to know the array length. The function sizeof(var) in C gives you the bytes in the computer memory. So if you know the memory the int occupy you can do like this:

如果你想知道数组有多少个数字,你想知道数组的长度。C 中的函数 sizeof(var) 为您提供计算机内存中的字节数。因此,如果您知道 int 占用的内存,您可以这样做:

int arraylength(int array[]) {
    return sizeof(array) / 4; // Size of the Array divided by the int size which is 4
}

回答by Gabriel Fernandez

Assuming you merely want to know the size of an array whose type you know (int) but whose size, obviously, you don't know, it is suitable to verify whether the array is empty, otherwise you will end up with a division by zero (causing a Float point exception).

假设你只是想知道一个数组的大小,它的类型你知道(int)但它的大小,显然你不知道,适合验证数组是否为空,否则你最终会被除以零(导致 a Float point exception)。

int array_size(int array[]) {
    if(sizeof(array) == 0) {
        return 0;
    }
    return sizeof(array)/sizeof(array[0]);
 }