There are several ways to initialize a C-style array in C++:
This leaves the array uninitialized, with indeterminate values:
int arr[3];
This initializes the array with the provided values:
int arr[3] = {1, 2, 3};
This also initializes the array with the provided values:
int arr[3]{1, 2, 3};
This initializes all elements to zero (or appropriate zero-equivalent for non-integral types):
int arr[3]{};
Here, the first three elements are initialized with the provided values, and the remaining elements are zero-initialized.:
int arr[5] = {1, 2, 3};
char
ArraysThis 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
.
Answers to questions are automatically generated and may not have been reviewed.
A detailed guide to working with classic C-style arrays within C++, and why we should avoid them where possible