Archived

This topic is now archived and is closed to further replies.

wannabe H4x0r

help! using sizeof() operator on an array

Recommended Posts

how do i find the size of an array allocated using the new keyword? i.e. long test[100]; cout << sizeof(test) << endl; //gives me 400 //but long *test; test = new long[100]; cout << sizeof(test) << endl; //gives me 4!!!! help! how do i get the size??

Share this post


Link to post
Share on other sites
You just need use the number of elements you allocated * sizeof(array)

I can''t think of a better way right now, except for possibly encapsulating the array into a class and have a size method, but that seems like too much work.

Share this post


Link to post
Share on other sites
The most important rule of thumb you will ever learn about sizeof is that it''s done at compile-time. The size it returns will be one known at compile-time. The size of a static array is known at compile-time, and thus the correct size is returned. However, the size of your dynamic array is unknown, so the best sizeof can do for you is return the size of the pointer, which is known at compile-time.

Share this post


Link to post
Share on other sites
quote:
Original post by TheAIDSVirus
Sigh?

----
AIDS

Some actually look it up in manuals, you know...
Wish I had an internet connection and a forum like this
when I started *sigh*



Share this post


Link to post
Share on other sites
quote:
Original post by Cold_Steel
You just need use the number of elements you allocated * sizeof(array)

I can''t think of a better way right now, except for possibly encapsulating the array into a class and have a size method, but that seems like too much work.


The work has already been done for you, std::vector comes with C++, and Boost has a static array wrapper.


  
#include <vector>
std::vector<int> dynamic_array;

#include <Boost\array.hpp>
boost::array<int, 200> static_array;



- Magmai Kai Holmlor

"Oh, like you''ve never written buggy code" - Lee

[Look for information | GDNet Start Here | GDNet Search Tool | GDNet FAQ | MSDN RTF[L] | SGI STL Docs | STFW | Asking Smart Questions ]

[Free C++ Libraries | Boost | ACE | Loki | MTL | Blitz++ | wxWindows| Spirit(xBNF)]
[Free C Libraries | zlib ]

Share this post


Link to post
Share on other sites