whats the difference between C Strings and C++ strings. Specially while doing dynamic memory allocation
You can (if you need one) always construct a C string out of a std::string by using the c_str() method. Show activity on this post. C++ strings are much safer,easier,and they support different string manipulation functions like append,find,copy,concatenation etc.
C-strings are usually faster, because they do not call malloc/new.
Use string. cstring is so 1970's. string is a modern way to represent strings in c++. you'll need to learn cstring because you will run into code that uses it.
Strings are used for storing text/characters. For example, "Hello World" is a string of characters. Unlike many other programming languages, C does not have a String type to easily create string variables.
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.
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!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With