What is the difference between std::string and a char array in C++?
| Point | std::string | char array |
|---|---|---|
| Size | Grows by itself | Fixed |
| Join | a + b | strcat (can overflow) |
| Compare | a == b | strcmp |
| Length | size() | strlen |
| Safety | Safe | Buffer 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. |