Re: Length of array
vikram_p_na...@yahoo.com wrote:
anali...@yandex.ru wrote:
There is _msize() function in Visual C compilers. It can be used with
following way:
template<class T> int ArrayLength(T* p)
{
return (_msize(p)/sizeof(T));
}
void main()
{
int *a=new int[10];
printf("array size: %d\n",ArrayLength(a));
delete[]a;
}
Not sure this is what the OP is looking for. What happens if a is not
dynamically allotted?
AFAIK, there is no way to find the size of the array.
If the size is not dynamically allocated, there's a portable way to
find the size if you have a reference to the array.
See example GetArrayLength below.
If it's dynamically allocated, you would have to use non-standard
methods, like using _msize.
Example code:
#include <iostream>
#include <malloc.h>
using namespace std ;
template<typename T>
class ConcreteArrayLength
{
private:
template <typename TT> struct deref_t {typedef TT type_t;};
template <typename TT> struct deref_t<TT*> {typedef typename
deref_t<TT>::type_t type_t;};
public:
typedef typename deref_t<T>::type_t ref_t;
typedef T type_t;
size_t operator()(ref_t &t)
{
return sizeof(t)/sizeof(t[0]);
}
private:
size_t operator()(ref_t *t);
};
template<class T>
size_t GetArrayLength(T& t) //Portable method
{
return ConcreteArrayLength<T>()(t);
}
template<class T> size_t GetArrayPtrLength(T& p)
{
return (_msize(p)/sizeof(T)); //Not portable method
}
int main()
{
int *dyn_alloc = new int[8];
cout << "dyn_alloc size: " << GetArrayPtrLength(dyn_alloc) << endl;
//cout << "dyn_alloc size: " << GetArrayLength(dyn_alloc) << endl;
//This will give compile time warning
int concrete_obj [] = { 1, 2, 3, 4, 5 } ;
cout << "concrete_obj size: " << GetArrayLength(concrete_obj) << endl;
//cout << "concrete_obj size: " << GetArrayPtrLength(concrete_obj) <<
endl; //Will give runtime error
delete[] dyn_alloc;
system("pause");
return 0 ;
}