I was using it in a function which gave me 1, and the way I posted gave me 1, but if I do this:
Is there any way to use it in a function?Code:cout << sizeof(arr) << "/" << sizeof(int) << "=" << sizeof(arr) / sizeof(int) << endl;
Printable View
I was using it in a function which gave me 1, and the way I posted gave me 1, but if I do this:
Is there any way to use it in a function?Code:cout << sizeof(arr) << "/" << sizeof(int) << "=" << sizeof(arr) / sizeof(int) << endl;
unfortunately it seems to be the language, arrays are not types, sizeof() works on both types and arrays. The best you can do is make a macro.
Code:
//template <class T>
//int length (T t){return sizeof(t) / sizeof(T);}; //returns 1
#define length(x) (sizeof(x)/sizeof(x[0])) //returns 5
Well, that's better than nothing, but it'll have to do. Thanks :)
but don't forget that you can use this ONLY in the function where you declared the array, therefore rendering it useless, because there the size is already known to you, if not the program. To let the program re-determine the size is bad habit.
PHP Code:#define length(x) (sizeof(x)/sizeof(x[0])) //returns 5
void func(int* arr);
void main()
{
int ar[30];
for(int i = 0; i < length(ar); i++) // useless, because you know that length is 30
ar[i] = 2;
func(ar);
}
void func(int* arr)
{
for(int i = 0; i < length(arr); i++) // length doesn't work here
{
arr[i] *= 2;
}
}
i know.. it's the language, unlike C++ BORK indentifiers will contain all type information, so for instance
ar[array(30)]
func(ar)
func#[@arr[31] ]
will not compile, because container is of type mutable*randomaccess*(static size)*container(30)
Won't that add a memory requirement overhead?