gpt4 book ai didi

c++ - C++中数组的元素计数

转载 作者:IT老高 更新时间:2023-10-28 21:44:40 24 4
gpt4 key购买 nike

假设我有一个数组arr。以下何时不给出数组元素的数量:sizeof(arr)/sizeof(arr[0])?

我只能处理一种情况:数组包含的元素属于数组类型的不同派生类型。

我说得对吗?是否存在(我几乎肯定一定存在)其他此类情况?

对不起,这个琐碎的问题,我是一名 Java 开发人员,而且我对 C++ 还很陌生。

谢谢!

最佳答案

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])?

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

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

Sample arr[10];
f(arr);

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

即使这是错误的:

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

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


编辑:

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

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++ - C++中数组的元素计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4839626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com