I'm writing a simple C++ code to count the number of elements in an array. I use template so that I can deal with arrays of different type.
template <typename T>
void count(T a[]){
cout << "size of array: " << sizeof(a) << endl;
cout << "size of element: " << sizeof(*a) << endl;
cout << "count number: " << sizeof(a)/sizeof(*a) << endl;
}
int main()
{
int x[6] ={1,2,3,4};
count(x);
cout << sizeof(x) << endl;
cout << sizeof(*x) << endl;
cout << sizeof(x)/sizeof(*x) << endl;
return 0;
}
But when I run this code, I got different results by using function count
and by just copying the same code in main
. I can't figure out why.
The results are like this:
size of array: 8
size of element: 4
count number: 2
24
4
6
What's more, when I use g++ compiler to run the code, there is a warning message:
warning:sizeof on array function parameter 'a' will return size of int* [-Wsizeof-array-argument]
cout << "size of array: " << sizeof(a) << endl;
This message did't show up when I use Code::Blocks running the code, but I think it might show my problem.
Where do these two different results come from?
It's because your template
:
template <typename T>
void count(T a[])
decays to:
template <typename T>
void count(T a*)
so you're printing the sizeof
a pointer, not of the array as your main
is.
The error message says this:
will return size of int*