Possible Duplicate:
Is there any way to determine the size of a C++ array programmatical开发者_如何学Cly? And if not, why?
Can I get the length of a dynamically allocated array in C++, if not, how does C++'s delete operator know how many elements to free.
I searched the forum and found that for dynamically allocated arrays, the length are stored in the four bytes before the array's header or somewhere else. How can I get this value?The four bytes before the header are definitely an implementation detail you shouldn't use. If you need to know the size of your array, use a std::vector.
In short, you can't. This is implementation defined, so you cannot access it. You can (and have to), however, store it in a variable, or use some types that control the size, such as std::vector
, std::string
, etc.
The delete[]
operator knows because the implementation of the C++ library has that information, but it is not available to the C++ program. In some implementations, that's the case, it is stored in some bytes before the actual address of the pointer, but again, you cannot know it.
You cannot. However, std::vector<T> v(N)
is almost exactly the same thing as new T[N]
and offers v.size()
, so you should really be using that, unless you have a terrific reason why you want to use the manual array.
Another option is to define your own allocator (overloading operator new[] and delete[] for whatever class you care about or doing #define malloc mymalloc and #define free myfree depending on your situation). Where you store your array length is up to you but generally one would allocate extra bytes (whatever amount is the proper amount for memory alignment - generally 4, 8, or 16) before the beginning of the array and store the length there.
精彩评论