← Back to C++ Course | Chapter 6: Arrays & Strings | Lesson 7 of 15

C++ Strings (C-style)

What is a C-style String?

A C-style string is just a character array with one special convention: it always ends with a null-terminator character, '\0', which marks where the actual text stops even if the array itself has extra unused space. Every standard C string function relies on finding that terminator to know where to stop reading.

Example: What is a C-style String?

cpp
#include <iostream>

int main() {
	char greeting[] = "Hi";
	std::cout << greeting << std::endl; // stops printing at the null-terminator
	return 0;
}

Declaring and Initializing

You can size a C-style string array explicitly, like char name[20];, leaving room to grow later, or let the compiler size it automatically from a string literal, like char name[] = "Alex";, which sizes the array to fit exactly the text plus the terminator.

Example: Declaring and Initializing

cpp
#include <iostream>
#include <cstring>

int main() {
	char name[20];
	strcpy(name, "Alex");
	char city[] = "Delhi"; // compiler sizes this automatically
	std::cout << name << " " << city << std::endl;
	return 0;
}

The Null-Terminator (\0)

The null-terminator is what distinguishes a C-style string from an ordinary array of characters — without it, functions like strlen() or cout << would have no way to know where meaningful text ends and leftover, uninitialized memory begins, and would keep reading (and likely crash or print garbage) past the intended end.

Example: The Null-Terminator (\0)

cpp
#include <iostream>
#include <cstring>

int main() {
	char word[] = {'H', 'i', '\0'};
	std::cout << word << " length=" << strlen(word) << std::endl;
	return 0;
}

Accessing and Modifying Characters

Individual characters inside a C-style string can be read or overwritten using ordinary array indexing, like name[0] = J;, exactly as you would with any other char array — just be careful never to overwrite or accidentally remove the terminating '\0'.

Example: Accessing and Modifying Characters

cpp
#include <iostream>

int main() {
	char name[] = "jack";
	name[0] = 'J';
	std::cout << name << std::endl;
	return 0;
}

Reading C-style Strings safely

Reading input directly into a C-style string with cin >> stops at the first whitespace character, which fails for anything containing spaces — cin.getline(buffer, size) instead reads an entire line up to a specified maximum length, safely avoiding a buffer overflow if the input is longer than expected.

Example: Reading C-style Strings safely

cpp
#include <iostream>

int main() {
	char fullName[50] = "Alex Johnson"; // cin >> would stop at the space
	std::cout << fullName << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.