Tutorial :C++ dynamic array sizing problem



Question:

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?


Solution:1

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.


Solution:2

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.


Solution:3

MyArray is of type int*. sizeof() when called on a variable returns the size of the type of that variable.

While there is a special case for arrays, it's only for stack arrays (i.e. int MyArray[3];).


Solution:4

MyArray is an int*, and sizeof(int*) on your system is 4.

MyArray is not an array. It is a pointer that happens to point to a block of memory in which you allocated an array.

int MyArray[10];  cout << sizeof(MyArray) << endl;  

That should print 40, which is how big 10 ints happens to be on your system. In this case, MyArray is an array. So the size of the type includes the size of all the elements of the array.

MyArray in this second case will decay into a pointer, but they are still two distinct types.


Solution:5

#include <iostream>    #define P(expr) std::cout << #expr << " = " << (expr) << std::endl    namespace {    void myFunction(size_t size) {      int *pointer = new int[size];       int MyArray[size];        P(size);      P(sizeof(MyArray));      P(sizeof(pointer));        delete [] pointer;        }  }  int main() {    myFunction(10);  }  

Output:

size = 10  sizeof(MyArray) = 40  sizeof(pointer) = 8  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »