You can treat this problem this way: builtin C array types have an automatic type conversion operator that can convert the array into a typed pointer (that points to the array).
An expression that evaluates to an array or array reference (for example the identifier of the array itself is one such expression) behaves as an array by default but this array expression can be automatically casted into a typed pointer by the compiler if the context requires that. In case of
sizeof
the compiler isn't forced to do the cast.
A conversion operator in action:
class MyArray
{
public:
MyArray()
{
memset(&m_Arr, 0, sizeof(m_Arr));
}
operator int*()
{
return m_Arr;
}
operator const int*() const
{
return m_Arr;
}
int& operator[](int index)
{
return m_Arr[5];
}
const int& operator[](int index) const
{
return m_Arr[5];
}
private:
int m_Arr[5];
};
void dojob(const int* p)
{
printf("%p", p);
}
void funcc()
{
MyArray arr;
int* p = arr;
dojob(arr);
}
EDIT: A type conversion operator (that I have written into my class) can convert any type to any other type but the conversion is used by the compiler implicitly only if it is necessary or if you ask the compiler to do so with a
static_cast
.
A pointer and an array are 2 different types, just there is a builtin auto conversion from array to typed pointer. Its also an accident that you can use both types as an array with the subscript (indexing []) operator. There is also pointer to array conversion in some cases:
void tfunc(int arr[5])
{
}
void Test()
{
int *p = NULL;
tfunc(p);
}
This is not a real conversion because when you declare a function parameter as an array, then it is only a pointer and the size I specified doesn't really matter.
sizeof(arr)
would be the same as the size of a pointer.