C++中数组的元素计数 [英] Element count of an array in C++

查看:34
本文介绍了C++中数组的元素计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组 arr.以下什么时候不会给出数组的元素数:sizeof(arr)/sizeof(arr[0])?

Let's say I have an array arr. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])?

我只能处理一种情况:数组包含具有数组类型的不同派生类型的元素.

I can thing of only one case: the array contains elements that are of different derived types of the type of the array.

我是对的吗?还有(我几乎肯定必须)其他这样的情况吗?

Am I right and are there (I am almost positive there must be) other such cases?

抱歉问了个小问题,我是一名 Java 开发人员,对 C++ 还很陌生.

Sorry for the trivial question, I am a Java dev and I am rather new to C++.

谢谢!

推荐答案

假设我有一个数组 arr.什么时候以下不会给数组的元素数:sizeof(arr)/sizeof(arr[0])?

Let's say I have an array arr. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])?

我经常看到新程序员这样做的一件事:

One thing I've often seen new programmers doing this:

void f(Sample *arr)
{
   int count = sizeof(arr)/sizeof(arr[0]); //what would be count? 10?
}

Sample arr[10];
f(arr);

所以新程序员认为 count 的值将是 10.但这是错误的.

So new programmers think the value of count will be 10. But that's wrong.

即使这是错误的:

void g(Sample arr[]) //even more deceptive form!
{
   int count = sizeof(arr)/sizeof(arr[0]); //count would not be 10  
}

这都是因为一旦你将一个数组传递给这些函数中的任何一个,它就会变成指针类型,所以 sizeof(arr) 将给出 的大小指针,不是数组!

It's all because once you pass an array to any of these functions, it becomes pointer type, and so sizeof(arr) would give the size of pointer, not array!

以下是一种优雅的方式,您可以将数组传递给函数,而不会让它衰减为指针类型:

The following is an elegant way you can pass an array to a function, without letting it to decay into pointer type:

template<size_t N>
void h(Sample (&arr)[N])
{
    size_t count = N; //N is 10, so would be count!
    //you can even do this now:
    //size_t count = sizeof(arr)/sizeof(arr[0]);  it'll return 10!
}
Sample arr[10];
h(arr); //pass : same as before!

这篇关于C++中数组的元素计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆