用C数组的元素数量++ [英] Element count of an array in C++
问题描述
比方说,我有一个数组改编
。当以下不给数组元素的数目:<?code>的sizeof(ARR)/ sizeof的(ARR [0])
我只能1箱子件事:数组包含不同派生类型的数组类型的元素
我的权利,并在那里(我几乎可以肯定存在的必须的定)等这样的情况?
对不起,琐碎的问题,我是一个Java开发我比较新的C ++。
谢谢!
比方说,我有一个数组ARR。什么时候
将以下不给
的数组的元素的数目:
的sizeof(ARR)/ sizeof的(ARR [0])?
块引用>有一件事情我经常看到新的程序员这样做:
无效F(样品* ARR)
{
诠释计数= sizeof的(ARR)/ sizeof的(ARR [0]); //会有什么算什么? 10?
}样品ARR [10];
F(ARR);所以,新的程序员认为
计数
的值将是10。但是,这是错误的。即使这是错误的:
无效克(ARR样品[])//更具有欺骗性的形式!
{
诠释计数= sizeof的(ARR)/ sizeof的(ARR [0]); //计数不会10
}这都是因为一旦你通过一个数组来任何的这些功能,就变成的指针的类型,所以
的sizeof(ARR)
会给大小的指针的,不是阵!编辑:
以下是你可以传递一个数组给函数一个优雅的方式,不让它腐烂成指针类型:
模板&LT;为size_t N'GT;
无效小时(样品(安培; ARR)[N])
{
为size_t计数= N; // N是10,所以会算!
//你甚至可以现在这样做:
//为size_t计数= sizeof的(ARR)/ sizeof的(ARR [0]);它会返回10个!
}
样品ARR [10];
H(ARR); //传递:和以前一样!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?
Sorry for the trivial question, I am a Java dev and I am rather new to C++.
Thanks!
解决方案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);
So new programmers think the value of
count
will be 10. But that's wrong.Even this is wrong:
void g(Sample arr[]) //even more deceptive form! { int count = sizeof(arr)/sizeof(arr[0]); //count would not be 10 }
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!
EDIT:
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屋!