0

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;
}
Peter
  • 397
  • 3
  • 13
  • [Here is a similar question. Or you could just use std::vector. (:][1] [1]: http://stackoverflow.com/questions/2034450/size-of-dynamically-allocated-array – Maryan Pritsak May 21 '15 at 07:49

3 Answers3

3

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

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

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

Basile Starynkevitch
  • 216,767
  • 17
  • 275
  • 509
0

You cannot compute the size of a dynamic array so you need to provide explicitly the size of the array.

#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;
}
alifirat
  • 2,789
  • 1
  • 15
  • 33
0

It cannot possibly work with sizeof, because sizeof is a compile-time operator, but you are asking for a runtime value. sizeof(dArray) is just syntactic sugar for sizeof(int*), and sizeof(*dArray) is just syntactic sugar for sizeof(int). Both are compile-time constants.

The reason why sizeof(array) works is that 5 is part of array's compile-time type (int[5]).

fredoverflow
  • 246,999
  • 92
  • 370
  • 646