C++ - C-Style Strings

Overview

Estimated time: 35–45 minutes

Use classic C strings for interop: char arrays with null termination. Prefer std::string but know how to convert and interact with C APIs.

Learning Objectives

  • Declare and initialize C strings (char[]).
  • Use functions (strlen, strcpy, strcmp) safely.
  • Convert between std::string and C strings.

Prerequisites

Declaring C strings

#include <cstring>
char s1[] = "hello";         // automatic null terminator
char s2[6] = {'h','e','l','l','o','\0'}; // explicit

Conversions

#include <string>
std::string a = "hi";
const char* c = a.c_str(); // view to internal buffer (valid while a unchanged)

Common Pitfalls

  • Forgetting the null terminator when constructing char arrays.
  • Using strcpy on overlapping or too-small buffers—prefer std::string operations.