如何找出动态分配的数组的大小(使用sizeof())?

时间:2015-05-21 07:42:29

标签: c++ arrays

我怎么能找出动态分配的数组的大小? 使用下面的方法使用普通数组工作正常,但我不能用动态分配的数组做同样的事情。请看一下,谢谢你的帮助。

#include <iostream>
using namespace std;


int main() {
    //normal array
    int array[5];
    cout << sizeof(array)/sizeof(array[0]) << endl; //this outputs the correct size

    //dynamically allocated array
    int *dArray = new int[5];
    //how to calculate and output the size here?

    return 0;
}

3 个答案:

答案 0 :(得分:3)

以便携式方式无法(从new获得真正分配的大小)。

您可以考虑定义自己的::operator new,但我不建议这样做。

您应该使用std::vector并了解有关C ++ standard containers的更多信息。

答案 1 :(得分:0)

您无法计算动态数组的大小,因此您需要明确提供数组的大小。

#include <iostream>
using namespace std;


int main() {
    //normal array

    int array[5];
    cout << sizeof(array)/sizeof(array[0]) << endl; //this outputs the correct size

    //dynamically allocated array
    int size = 5; // array size
    int *dArray = new int[size];


    return 0;
}

答案 2 :(得分:0)

它不可能与sizeof一起使用,因为sizeof是编译时运算符,但是您要求运行时值。 sizeof(dArray)只是sizeof(int*)的语法糖,而sizeof(*dArray)只是sizeof(int)的语法糖。两者都是编译时常量。

sizeof(array)有效的原因是5array编译时类型(int[5])的一部分。

相关问题