help! using sizeof() operator on an array
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??
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.
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 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
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 ]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement