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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.