Size of array (new[])

前端 未结 4 1469
挽巷
挽巷 2021-01-21 19:17

In debug heap I can get size of array, which was created by new[]:

int size = *((int *)((char *)ptr - 16));

It is working correctl

4条回答
  •  误落风尘
    2021-01-21 20:17

    Like this:

    std::vector< int > array( 1024 ); // allocate 1024 element array.
    int size = array.size();
    int sizeInBytes = size * sizeof( int );
    

    ;)

    It really is the best way what you are trying to do is take adavantage of something which is COMPLETELY compiler/library dependent ... Its a really bad thing to do, in general, as your code becomes completely unportable not even mentioning that the next version of your compiler may come with a different memory allocation implementation which breaks what you are trying to do ...

提交回复
热议问题