help! using sizeof() operator on an array

Started by
6 comments, last by wannabe H4x0r 21 years, 1 month ago
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??
Advertisement
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.
______________________________"Man is born free, and everywhere he is in chains" - J.J. Rousseau
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.
damn, i didnt know that, it doesnt look like a precomplile macro or anything... but thanks ppl
Sigh...


Update GameDev.net system time campaign - success at last
Arguing on the internet is like running in the Special Olympics: Even if you win, you're still retarded.[How To Ask Questions|STL Programmer's Guide|Bjarne FAQ|C++ FAQ Lite|C++ Reference|MSDN]
Sigh?

----
AIDS
----AIDS
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*



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 ]

- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara

This topic is closed to new replies.

Advertisement