C-Style Arrays

Alternatives to C-Style Arrays

What are some alternatives to using C-style arrays in C++?

Abstract art representing computer programming

While C-style arrays have their uses, they come with several pitfalls and limitations. Modern C++ offers some powerful alternatives:

std::array

The primary use for std::array is for fixed-size arrays. They have the following properties:

  • Keeps size information and provides bounds-checked access with .at().
  • Supports iterators and STL algorithms.
  • Size must be known at compile time.
#include <array>

std::array<int, 3> arr = {1, 2, 3};

std::vector 

When we need an array whose size needs to change at run time, std::vector is the typical choice. They have the following properties:

  • Dynamically resizable.
  • Also supports bounds-checked access, iterators, and STL algorithms.
  • Size can be changed at runtime.
#include <vector>

std::vector<int> vec = {1, 2, 3};
vec.push_back(4);

std::string (for strings)

When we have a text string (a collection of characters), the standard library’s std::string type is ideally suited.

  • Specifically designed for string handling.
  • Supports various string operations and manipulations.
#include <string>

std::string str = "Hello";

std::span (for array views, since C++20)

When we want a general view of an array that does not own the underlying collection, we can use a std::span. They have the following properties:

  • Provides a view into a contiguous sequence of objects.
  • Can be used to pass arrays (or parts of arrays) to functions without decay.
  • Non-owning view, does not manage the lifetime of the underlying data.
#include <span>

void func(std::span<int> sp) {
// Work with sp
}

int main() {
    int arr[] = {1, 2, 3};
    func(arr);
}

These alternatives provide safer, more flexible, and more expressive ways to work with collections of objects in C++. They integrate well with the rest of the Standard Library and support modern C++ idioms.

However, C-style arrays still have their place, particularly when interacting with C code or in low-level programming. Understanding both C-style arrays and their modern alternatives is important for writing effective C++ code.

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

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:

  • 124 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