开发者

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?


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.


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];).


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.


#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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜