如何找出动态分配的数组的大小是多少(使用sizeof())? [英] How to find out what the size of dynamically allocated array is(using sizeof())?

查看:72
本文介绍了如何找出动态分配的数组的大小是多少(使用sizeof())?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何找出动态分配的数组的大小?对于普通数组,使用以下方法可以正常工作,但对于动态分配的数组,我无法做同样的事情.请看一下,谢谢您的帮助.

how could I find out the size of dynamically allocated array? With normal array using the method below works fine, but I can't do the same thing with dynamically allocated array. Please, have a look and thanks for your help.

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

推荐答案

不可能(通过 new 获得真正分配的大小).

It is not possible (to get the really allocated size from a new) in a portable manner.

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

You could consider defining your own ::operator new but I don't recommend doing this.

您应该使用 std :: vector 并了解有关C ++的更多信息<一个href ="http://en.cppreference.com/w/cpp/container" rel ="nofollow">标准容器.

You should use std::vector and learn a lot more about C++ standard containers.

这篇关于如何找出动态分配的数组的大小是多少(使用sizeof())?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆