You are here

Using the Sizeof Operator with Arrays in C++

10 February, 2015 - 16:49

Example 18.2: using the sizeof operator

int ages[] = {49,48,26,l9,l6}; int counter; 
for (counter = 0, counter < sizeof ages 1 sizeof ages[0], counter++)   {   cout « ages[counterJ « endl;   } 

Within the control of the for loop for the displaying of the grades, note that we calculated the number of the members in the array by using the sizeof operator. The expression is:

sizeof ages 1 sizeof ages[0]

When you ask for the sizeof an array identifier name the answer is how many total bytes long is the array (or in other words how many bytes of storage does this array need to store its values). This will depend on the data type of the array and the number of elements. When you ask for the sizeof one of its members, it tells you how many bytes one member needs. By dividing the total number of bytes by the size of one member, we get the answer we want: the number of members in the array. This method allows for fexible coding. By writing the for loop in this fashion, we can change the declaration of the array by adding or subtracting members and we don't need to change our for loop code.