Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ dynamic array sizing problem

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?

like image 812
Peter Avatar asked Mar 14 '26 08:03

Peter


2 Answers

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.

like image 144
James McNellis Avatar answered Mar 16 '26 21:03

James McNellis


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.

like image 21
GManNickG Avatar answered Mar 16 '26 22:03

GManNickG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!