Labs ICT
Pro Login

C-Style Strings

Before C++ had the std::string class, there were C-style strings — just arrays of characters terminated by a null character ('\0'). You still see them in older code and when interacting with C libraries, so understanding them matters.

Declaring C-Style Strings

A C-string is a char array. The null terminator marks the end of the string. When you use a string literal, the compiler adds it automatically:

#include <iostream>

int main() {
  char name[] = "Alice";
  char greeting[20] = "Hello";

  std::cout << name << "\n";
  std::cout << greeting << "\n";

  char city[10] = {'N', 'Y', 'C', '\0'};
  std::cout << city << "\n";
  return 0;
}

Notice that "Alice" actually takes up 6 bytes — the five letters plus the hidden null terminator.

Common Functions

The <cstring> header provides functions to work with C-strings. Here are the three you will use most often:

#include <iostream>
#include <cstring>

int main() {
  char src[20] = "Hello";
  char dest[20];

  strcpy(dest, src);
  std::cout << "Copied: " << dest << "\n";

  std::cout << "Length of src: " << strlen(src) << "\n";

  char a[] = "apple";
  char b[] = "banana";

  int result = strcmp(a, b);
  if (result < 0) {
    std::cout << "apple comes before banana\n";
  } else if (result > 0) {
    std::cout << "apple comes after banana\n";
  } else {
    std::cout << "they are equal\n";
  }
  return 0;
}

strcpy copies one string into another. strlen returns the length (excluding the null terminator). strcmp compares two strings lexicographically and returns a negative, zero, or positive value.

Why C++ Strings are Safer

C-strings are dangerous because you can easily overflow the buffer. If you copy a string that is longer than the destination array, you get a buffer overflow — a common security vulnerability. Modern C++ code prefers std::string for this reason, but knowing C-strings is still essential for maintaining legacy code and working with low-level APIs.