tags:

views:

199

answers:

2

whats the difference between C Strings and C++ strings. Specially while doing dynamic memory allocation

+11  A: 

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.

paxdiablo
`std::string` are objects with...
dmckee
Damn you c_str()!
Ed Swangren
+1  A: 

In C, strings are just char arrays which, by convention, end with a NULL byte. And you must be responsible for the memory management using malloc, realloc, free, which always is considered to be a nightmare

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, thus it can increase automatically

Emacs