In C++ given an array like this:
unsigned char bogus1[] = {
0x2e, 0x2e, 0x2e, 0x2e
};
Is there a way to introspect bogus1 to find out is is four characters long?
In C++ given an array like this:
unsigned char bogus1[] = {
0x2e, 0x2e, 0x2e, 0x2e
};
Is there a way to introspect bogus1 to find out is is four characters long?
Sure:
#include <iostream>
int main()
{
unsigned char bogus1[] = {
0x2e, 0x2e, 0x2e, 0x2e
};
std::cout << sizeof(bogus1) << std::endl;
return 0;
}
emits 4
. More generally, sizeof(thearray)/sizeof(thearray[0])
is the number of items in the array. However, this is a compile-time operation and can only be used where the compiler knows about that "number of items" (not, for example, in a function receiving the array as an argument). For more generality, you can use std::vector
instead of a bare array.
One thing to be careful about with sizeof
is making sure you don't accidentally do the sizeof an array that has decayed into a pointer:
void bad(int a[10])
{
cout << (sizeof(a) / sizeof(a[0])) << endl;
}
int main()
{
int a[10];
cout << (sizeof(a) / sizeof(a[0])) << endl;
bad(a);
}
On my 64 bit machine, this outputs:
10
2
The size computed inside bad
is incorrect because a
will have decayed to a pointer. In general, don't trust the sizeof
an array that was passed as a function argument.
This gets around the pointer decay problem:
#include <cstddef>
template<typename T, std::size_t N>
std::size_t array_size(T(&)[N]) { return N; }
In that it will not compile unless the array size is known.