Discussion: Sizing Up Some Characters
Explore how the sizeof operator works with character arrays and pointers in C++. Understand the difference between array and pointer types, how to accurately count array elements, and why the sizeof operator behaves differently in function parameters. This lesson will help you write safer, clearer C++ code by using modern containers and recognizing potential pitfalls related to array size and pointer conversions.
Run the code
Now, it’s time to execute the code and observe the output.
Understanding the output
The program defines a characters array with three elements. We then print the size of this array in various ways. What does the sizeof operator do in each case? Which of them are defined by the standard, and which are implementation-defined? And what do they print on the computer?
Defining the array
First, the program defines a char characters[] = {'a', 'b', 'c'} array. We then print the size of this array using the sizeof operator. The sizeof operator yields the number of bytes occupied by its operand, which in this case is 3, since each char is one byte, and there are three of them.