sizeof(files) / sizeof(files[0])
is being used to calculate the number of elements in an array.
given an array declared like this:
int files[] = {1,2,3,4,5};
The compiler will calculate the array size from the given number of initializer values.
In this case the compiler know the array has 5 elements.
So
sizeof(files)
will return 5 *sizeof(int) - which assuming sizeof an integer is 4 bytes will give us a value 0f 20 bytes for the sizeof the entire array.
sizeof(files[0])
will give us the size in bytes of the first element in the array (for this example we are assuming size of integer is 4 bytes).
So
sizeof(files) / sizeof(files[0])
will give 20/4 = 5 elements in the array.
Note:
This calculation can only be used in the scope of the function in which the array is declared because when you pass an array to another function you are not really passing an array, you will be passing a pointer
(in this case you will be passing an
int *
)and the calculation would make no sense in the function that is called.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
void wrong_array_size_calculation_function( int files [])
{
cout << sizeof(files) / sizeof(files[0]) << endl; //wrong
}
int main()
{
int files[] = {1,2,3,4,5};
cout << sizeof(files) / sizeof(files[0]) << endl; //ok
wrong_array_size_calculation_function( files);
return 0;
}
|