【问题标题】:How to find out what the size of dynamically allocated array is(using sizeof())? [duplicate]如何找出动态分配数组的大小(使用 sizeof())? [复制]
【发布时间】:2015-08-02 18:05:19
【问题描述】:

我怎样才能知道动态分配数组的大小? 使用以下方法的普通数组可以正常工作,但我不能对动态分配的数组做同样的事情。请查看并感谢您的帮助。

#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;
}

【问题讨论】:

标签: c++ arrays


【解决方案1】:

以可移植的方式(从new 获取真正分配的大小)是不可能的。

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

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

【讨论】:

    【解决方案2】:

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

    #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;
    }
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2021-01-15
        • 2013-04-07
        • 2012-11-15
        • 1970-01-01
        • 2011-01-03
        • 2011-02-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多