C-Style Arrays

C-Style Array Initialization

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

Abstract art representing computer programming

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.

This Question is from the Lesson:

C-Style Arrays

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

C-Style Arrays

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved