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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…