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. But if I use sizeof(people)
in the main function, it returns 300, which is right. 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?
#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
.
the value of sizeof(array) seems to be 4, which is obviously wrong. But if I use sizeof(people) in the main function, it returns 300, which is right. I wonder why?
That is because array
, despite its name, and despite what the declaration looks like, is not an 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?
No. people
is not a pointer. It is an array.
Just fix the functions: getArrayLen
& test
to general function:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.