What is the function of "sizeof(num1) / sizeof(num2[0])" ? |
sizeof(num1) returns the size of the array in bytes.
sizeof(num2[0]) returns the size of the first element in bytes.
Dividing the size of the array by the size of the first elment gives you the number of elements in the array.
IMO,
rezy3312's approach is overly pedantic and subject to subtle errors. Note that
(sizeof(num1) / sizeof(num2[0])
refers to two different arrays. If the type of one of the two arrays is changed in the future, the result will be wrong. If you're going to use this approach, it is better to use the same array.
(sizeof(num1) / sizeof(num1[0])
and
(sizeof(num2) / sizeof(num2[0])
when referring to the second array.
A simpler and shorter approach is to create a constant defining the size of the arrays.
|
const int ARRAY_SIZE = 10;
|
Now, anywhere you would use 10 or
(sizeof(num1) / sizeof(num1[0])
, you use ARRAY_SIZE instead.