I know that the sizeof operator returns the size of any given type in C/C++. In C style arrays the name of the array is a pointer itself that points to the first element of the array. For example, in int arr[2] = {2, 3}, *arr will yield 2. Then why the sizeof operator does not return the size of the pointer variable, instead it returns the total size occupied by the array in the memory.
See this code:
#include <iostream>
using namespace std;
int main()
{
int arr[10];
cout << sizeof (arr);
return 0;
}
Output: 40 bytes (Given int takes 4 bytes)
What I want to ask in this code is that even if arr is just a pointer then how does sizeof returns the entire size occupied by this array?
I wrote my own sizeof to understand it:
#include <iostream>
using namespace std;
template <typename T>
size_t my_sizeOf(T var)
{
return (char *) (&var + 1) - (char *) (&var);
}
int main()
{
int arr[10];
cout << my_sizeOf(arr);
return 0;
}
Output: 8 bytes (Given pointer variable takes 8 bytes)
And this code prints only the size of the pointer variable now. Am I missing some crucial point about the sizeof operator?