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

C++ Array of Strings

C-style Array of Strings

A C-style array of strings can be declared as a 2D character array, like char names[3][10];, where the first dimension counts how many strings you have and the second caps how many characters (including the terminator) each individual string can hold. This rigid per-string size limit is exactly what modern C++ tries to avoid.

Example: C-style Array of Strings

cpp
#include <iostream>

int main() {
	char names[3][10] = {"Alice", "Bob", "Carol"};
	std::cout << names[0] << " " << names[1] << std::endl;
	return 0;
}

C++ std::string Array

The modern approach declares an ordinary array of std::string objects, like string names[3];, where each element manages its own memory and can grow to whatever length it needs — there's no fixed character limit to worry about per string, unlike the C-style 2D array approach.

Example: C++ std::string Array

cpp
#include <iostream>
#include <string>

int main() {
	std::string names[3];
	names[0] = "Alice";
	std::cout << names[0] << std::endl;
	return 0;
}

Initializing String Arrays

You can populate a string array right at declaration using an initializer list, like string days[] = {"Mon", "Tue", "Wed"};, and just as with numeric arrays, the compiler will automatically count the elements to size the array if you leave the brackets empty.

Example: Initializing String Arrays

cpp
#include <iostream>
#include <string>

int main() {
	std::string days[] = {"Mon", "Tue", "Wed"};
	std::cout << days[1] << std::endl;
	return 0;
}

Accessing and Modifying Strings

Individual strings inside the array are accessed with a single index, like names[1], and since each element is a full std::string, you can immediately call any string method on it, like names[1].append("son");, to modify that specific entry in place.

Example: Accessing and Modifying Strings

cpp
#include <iostream>
#include <string>

int main() {
	std::string names[] = {"Alice", "Bob"};
	names[1] = "Bobby";
	std::cout << names[1] << std::endl;
	return 0;
}

Iterating Through String Arrays

A regular indexed for loop or a range-based for loop can both walk through a string array — the indexed version is useful when you also need to know each string's position, while the range-based version is cleaner when you only care about the string values themselves.

Example: Iterating Through String Arrays

cpp
#include <iostream>
#include <string>

int main() {
	std::string days[] = {"Mon", "Tue", "Wed"};
	for (const std::string &day : days) {
		std::cout << day << " ";
	}
	std::cout << 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.