Search⌘ K

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.

C++
#include <iostream>
void serialize(char characters[])
{
std::cout << sizeof(characters) << "\n";
}
int main()
{
char characters[] = {'a', 'b', 'c'};
std::cout << sizeof(characters) << "\n";
std::cout << sizeof(characters) / sizeof(characters[0]) << "\n";
serialize(characters);
}

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.

The sizeof()

...