C-Style Array Initialization

What are the different ways to initialize a C-style array in C++?

There are several ways to initialize a C-style array in C++:

Default Initialization (no initializer)

This leaves the array uninitialized, with indeterminate values:

int arr[3];

Initializer List

This initializes the array with the provided values:

int arr[3] = {1, 2, 3};

Uniform Initialization (since C++11)

This also initializes the array with the provided values:

int arr[3]{1, 2, 3};

Zero Initialization

This initializes all elements to zero (or appropriate zero-equivalent for non-integral types):

int arr[3]{};

Partial Initialization

Here, the first three elements are initialized with the provided values, and the remaining elements are zero-initialized.:

int arr[5] = {1, 2, 3};

String Literal for char Arrays

This is a special case for initializing a char array with a string literal. It automatically includes the null terminator.

char str[] = "Hello";

Remember, the size of the array must be known at compile time when declaring it on the stack. If you need runtime sizing, consider dynamic allocation with new[] or using std::vector.

C-Style Arrays

A detailed guide to working with classic C-style arrays within C++, and why we should avoid them where possible

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

sizeof and C-Style Arrays
Why does sizeof return the total bytes of a C-style array, but return the size of a pointer when the array is passed to a function?
Out of Bounds Access in C-Style Arrays
What happens if I try to access an element outside the bounds of a C-style array?
C-Style Array to Pointer Decay
What does it mean when a C-style array "decays" to a pointer?
Alternatives to C-Style Arrays
What are some alternatives to using C-style arrays in C++?
2D C-Style Arrays
How do I create and work with 2D C-style arrays in C++?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant