An array definition with initialization, the number of elements can be omitted, that is, the expression in square brackets can be omitted. At this point, the number of elements that are finalized depends on the number of initialized values. For example:
1#include <iostream>2 using namespacestd;3 intMain ()4 {5 intA[] = {1,2,3,4,5};6 for(inti =0; I <sizeof(a)/sizeof(a[0]); ++i)7cout << A[i] <<" ";8cout <<"\ n";9Cin.Get();Ten return 0; One}
Operation Result:
In the program, sizeof (a) is used, that is, the number of bytes in the A array. There is also sizeof (a[0]), which is the number of bytes of space occupied by the first element, because it is a shaped array, so it is equivalent to sizeof (int), and the number of degrees in the 32-bit compiler is 4. A array has several elements, each of which has sizeof (A[0]) bytes, so dividing the two is the number of elements. This expression is intended to be maintainable. (because the number of array elements may also change as programming needs occur.) In a slightly larger programming, the input process is often separated from the processing process, that is, there are many statements in the middle, so it is not immediately possible to visually see the value of the number of array elements, and according to the array name and its elements of information, the way to get the number of elements, with good versatility. The structure description of the For loop does not have to be changed with the initialization of the array)
C + + code: Array initialization