The basic pseudo code looks like this:
void myFunction()
{
int size = 10;
int * MyArray;
MyArray = new int[size];
cout << size << endl;
cout << sizeof(MyArray) << endl;
}
The first cout returns 10, as expected, while the second cout returns 4.
Anyone have an explanation?
MyArray is only a pointer, which on your system, has a size of four bytes.
When you dynamically create an array, you need to keep track of the size yourself.
If you created an automatic array or static array,
int MyArray[10];
then sizeof(MyArray) would be 40. As soon as the array decays to a pointer, though, e.g. when you pass it to a function, the size information is lost.
Related to a recent question.
A pointer is a pointer, regardless of what it points at. You have to keep track of the size yourself. Better is to use a std::vector.
sizeof returns the size of an expression, which in this case is the size of the type int*. This always has the same size, regardless of its value.
For comparison, consider:
int i = 0;
i = 23434634;
No matter what value i takes on, the size of i itself is still only sizeof(i) == sizeof(int). A pointer is the same, it just holds a different kind of value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With