【问题标题】:get the size of heap array in c++ [duplicate]在c ++中获取堆数组的大小[重复]
【发布时间】:2015-04-04 19:44:52
【问题描述】:

代码1:

int * a;
a=new int[222];
cout<<"the size of a is "<<sizeof(a)<<endl;

输出1:

the size of a is 8

代码2:

int * a;
a=new int[222];
cout<<"the size of a is "<<a.length()<<endl;

输出2:

error: member reference base type 'int *' is not a structure or
  union

如何获取堆数组的大小?谢谢..

【问题讨论】:

  • 使用std::vector。更易于使用且不易发生内存泄漏

标签: c++ arrays heap-memory


【解决方案1】:

简短的回答是,它不能完成,至少不能以便携的方式完成。您需要以某种方式分别跟踪数组的大小(例如,在整数变量或类似变量中)。

【讨论】:

    【解决方案2】:

    使用容器而不是原始指针:

    std::vector<int> a(222);
    cout << "the size of a is " << a.size(); << endl;
    

    【讨论】:

      猜你喜欢
      • 2013-04-12
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 2014-04-30
      • 2020-07-19
      • 2011-05-05
      • 1970-01-01
      相关资源
      最近更新 更多