I have a section of code in which two array are declared with sizes of 6 and 13, but when \'sizeof()\' is used the lengths are returned as 12 and 26.
#includ
sizeof returns the size in bytes, which for an array is the number of items × the size of each item. To get the number of items divide by the size of one element.
sizeof(races) / sizeof(races[0])
Be careful with this. It will only work for arrays whose size is known at compile time. This will not work:
void func(short int array[])
{
// DOES NOT WORK
size_t size = sizeof(array) / sizeof(array[0]);
}
Here array is actually a short int * and sizeof(array) does not return the actual size of the array, which is unknown at compile time.
This is one of many reasons to prefer std::vector or std::array to raw arrays in C++.