whats the difference between C Strings and C++ strings. Specially while doing dynamic memory allocation
C++ strings are much safer,easier,and they support different string manipulation functions like append,find,copy,concatenation etc.
one interesting difference between c string and c++ string is illustrated through following example
#include <iostream>
using namespace std;
int main() {
char a[6]; //c string
a[5]='y';
a[3]='o';
a[2]='b';
cout<<a;
return 0;
}
output »¿boRy¤£f·Pi»¿
#include <iostream>
using namespace std;
int main()
{
string a; //c++ string
a.resize(6);
a[5]='y';
a[3]='o';
a[2]='b';
cout<<a;
return 0;
}
output boy
I hope you got the point!!
The difference is speed in some operations, and encapsulation of places where common errors occur. std::string maintains information about the content and length of the string. This means it is not prone to buffer overruns in the same way a const char * is. It will also be faster for most operations than a const char * because the length of the string is known. Most of the cstring operations call strlen() under the hood to find out the length of the string before operating on it, this will kill performance. std::string is compatible with STL algorithms and other containers.
Lastly, std::string doesn't have the same "gotcha!" moments a char * will have:
I hardly know where to begin :-)
In C, strings are just char
arrays which, by convention, end with a NUL byte. In terms of dynamic memory management, you can simply malloc
the space for them (including the extra byte). Memory management when modifying strings is your responsibility:
char *s = strdup ("Hello");
char *s2 = malloc (strlen (s) + 6);
strcpy (s2, s);
strcat (s2, ", Pax");
free (s);
s = s2;
In C++, strings (std::string
) are objects with all the associated automated memory management and control which makes them a lot safer and easier to use, especially for the novice. For dynamic allocation, use something like:
std::string s = "Hello";
s += ", Pax";
I know which I'd prefer to use, the latter. You can (if you need one) always construct a C string out of a std::string
by using the c_str()
method.