What is the difference between std::string and a char array in C++?

Pointstd::stringchar array
SizeGrows by itselfFixed
Joina + bstrcat (can overflow)
Comparea == bstrcmp
Lengthsize()strlen
SafetySafeBuffer overflow risk
#include <cstring>
#include <iostream>
#include <string>

int main() {
    std::string s = "Hello";
    s += " World";
    std::cout << s << ' ' << s.size() << '\n';

    char c[] = "Hello";
    std::cout << sizeof(c) << ' ' << std::strlen(c) << '\n';      // 6 bytes (with \0), 5 characters
}
Output

Hello World 11
6 5

See C++ Strings.


Learn more about the similar topics:
Tutorials
C++ Strings: std::string and string_view
C++ Arrays and std::array
C++ Vectors (std::vector)
Exercises & Assignments
Reverse a string
Check if a string is a palindrome
Count the vowels in a string
Find the second largest number in a vector
Sort a vector with bubble sort
Transpose a matrix
Interview Questions & Answers
What is the difference between an array and a vector in C++?
What is the difference between std::string and a char array in C++?