I have an array and want to detect the size of the array. If I do this, it will return the correct length:
main()
{
int a = { 1, 2, 3};
int len = sizeof a / sizeof a[0];
// return correct length = 3
cout << "the correct length is " << len << endl;
}
But if put it in this way, it doesn't work:
int length(*v);
// or
// int length(v[]);
main()
{
int a = { 1, 2, 3};
int len = length(a);
// it only returns length = 1
cout << "the vector length is " << len << endl;
}
int length(*v)
{
return sizeof v / sizeof v[0];
}
// end code
I know the reason is in the function length(*v) it only use the first element of v (since v is a pointer now) to do the size calculation. That is why it returns 1. But what is the right way to return a array size from a function?
main()
{
int a = { 1, 2, 3};
int len = sizeof a / sizeof a[0];
// return correct length = 3
cout << "the correct length is " << len << endl;
}
But if put it in this way, it doesn't work:
int length(*v);
// or
// int length(v[]);
main()
{
int a = { 1, 2, 3};
int len = length(a);
// it only returns length = 1
cout << "the vector length is " << len << endl;
}
int length(*v)
{
return sizeof v / sizeof v[0];
}
// end code
I know the reason is in the function length(*v) it only use the first element of v (since v is a pointer now) to do the size calculation. That is why it returns 1. But what is the right way to return a array size from a function?