[英]How can I design a function that can return the length of an array easily?
I want to design a function that can return the value of an array easily.我想设计一个可以轻松返回数组值的函数。 But I meet some problems.但是我遇到了一些问题。 In the return statement of function getArrayLen()
, the value of sizeof(array)
seems to be 4, which is obviously wrong.在函数getArrayLen()
的 return 语句中, sizeof(array)
的值似乎是 4,这显然是错误的。 But if I use sizeof(people)
in the main function, it returns 300, which is right.但是如果我在主函数中使用sizeof(people)
,它返回 300,这是正确的。 I wonder why?我想知道为什么? I konw that sizeof(array)
returns 4 because "array" is a pointer, but isn't "people" in sizeof(people)
a pointer, too?我知道sizeof(array)
返回 4 因为“array”是一个指针,但sizeof(people)
的“people”不是一个指针吗?
#include <iostream>
#include <string>
using namespace std;
template <class T>
int getArrayLen(T& array)
{
cout << "size of array: " << sizeof(array) << endl;
cout << "size of array[0]: " << sizeof(array[0]);
return (sizeof(array) / sizeof(array[0]));
}
struct Person
{
string name;
int age;
string sex;
};
void test(Person arr[])
{
int length = getArrayLen(arr);
}
int main()
{
Person people[5] =
{
{"John",23,"Male"},
{"Alan",22,"Male"},
{"Alex",20,"Male"},
{"James",21,"Male"},
{"Lucy",19,"Male"}
};
test(people);
return 0;
}
How can I design a function that can return the length of an array easily?如何设计一个可以轻松返回数组长度的函数?
You could use a function template that deduces the size from an array argument.您可以使用从数组参数中推导出大小的函数模板。 However, there is no need to design such template, because standard library provides one already: std::size
.然而,没有必要设计这样的模板,因为标准库已经提供了一个: std::size
。
the value of sizeof(array) seems to be 4, which is obviously wrong. sizeof(array)的值好像是4,这显然是错误的。 But if I use sizeof(people) in the main function, it returns 300, which is right.但是如果我在主函数中使用 sizeof(people) ,它返回 300,这是正确的。 I wonder why?我想知道为什么?
That is because array
, despite its name, and despite what the declaration looks like, is not an array.那是因为array
尽管它的名字和声明看起来像,但它不是一个数组。 A function parameter is never an array.函数参数永远不是数组。
The parameter is a pointer which happens to an element of an array.参数是一个指向数组元素的指针。 Your function cannot be used to get the size of an array using a pointer to an element of the array.您的函数不能用于使用指向数组元素的指针来获取数组的大小。
but isn't "people" in sizeof(people) a pointer, too?但 sizeof(people) 中的“people”不也是一个指针吗?
No. people
is not a pointer.不, people
不是指针。 It is an array.它是一个数组。
Just fix the functions: getArrayLen
& test
to general function:只需修复函数: getArrayLen
& test
到一般函数:
template <class T>
int getArrayLen(const T& array) {
return sizeof(T);
}
template <class T>
void test(const T& array)
{
int length = getArrayLen(array);
cout << length << endl;
}
Result:结果:
300
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.