Functions like strcpy()
come from C and they are very "low-level". They involve a lot of manual accounting for how-much-memory-is-allocated-where. It's quite easy to make mistakes with them. And you made one!
As others have said: if your point of confusion was "why didn't the compiler stop me from doing this", the answer is that you were using a method of handling strings with very little checking. The good news about C++ is that it offers that low-level ability when you need it, but also comes with nice classes in the standard library to help.
So for instance, there is std::string:
#include <string>
#include <iostream>
using namespace std;
int main() {
string a = "abc";
cout << a << a.length();
a = "abcdefgh";
cout << a << a.length();
// Note: it's okay to leave off return in C++, for main() only!
}
That should give you:
abc 3
abcdefgh 8
Notice that even the issue of the null terminator has been handled for you, so you don't have to worry about it. You can append strings together using "+" and do many things you'd expect from other languages, yet with a lot more control over how and when copies are made (when you need it).
All this said: there are better ways to learn very early C++ concepts than asking on StackOverflow. That's likely to make people mad that you haven't made the effort to work through a good book or tutorial! So consider taking that initiative:
The Definitive C++ Book Guide and List
And if your interest is in learning C and sticking to really low-level stuff, I'd suggest staying in C. If you are writing new code and it's a mix of strlen()
along with cout <<
, that's probably not the best idea.