The compile time unary operator sizeof determines the size in bytes of a built-in array or of any other data type, variable or constant during program compilation. When applied to a built-in array’s name, as in Fig. 8.13 (line 13), the sizeof
operator returns the total number of bytes in the array as a value of type size_t
. The computer we used to compile this program stores variables of type double
in 8 bytes of memory, and numbers
is declared to have 20 elements (line 11), so it uses 160 bytes in memory. When applied to a pointer parameter (line 22) in a function that receives a built-in array as an argument, the sizeof
operator returns the size of the pointer in bytes (4 on the system we used)—not the built-in array’s size.
1 // Fig. 8.13: fig08_13.cpp
2 // Sizeof operator when applied to a built-in array's name
3 // returns the number of bytes in the built-in array.
4 #include <iostream>
5 using namespace std;
6
7 size_t getSize( double * ); // prototype
8
9 int main()
10 {
11 double numbers[ 20 ]; // 20 doubles; occupies 160 bytes on our system
12
13 cout << "The number of bytes in the array is " << sizeof( numbers );
14
15 cout << "
The number of bytes returned by getSize is "
16 << getSize( numbers ) << endl;
17 } // end main
18
19 // return size of ptr
20 size_t getSize( double *ptr )
21 {
22 return sizeof( ptr );
23 } // end function getSize
The number of bytes in the array is 160
The number of bytes returned by getSize is 4
Common Programming Error 8.3
Using the sizeof operator in a function to find the size in bytes of a built-in array parameter results in the size in bytes of a pointer, not the size in bytes of the built-in array.
The number of elements in a built-in array can be determined using the results of two sizeof
operations. For example, to determine the number of elements in the built-in array numbers
, use the following expression (which is evaluated at compile time):
sizeof numbers / sizeof( numbers[ 0 ] )
The expression divides the number of bytes in numbers
(160, assuming 8 byte double
s) by the number of bytes in the built-in array’s zeroth element (8)—resulting in the number of elements in numbers
(20).