Container: C StringTrail Index | References and Pointers | C String Briefly: do NOT use C strings except for the most trivial tasks (constants).
Use C Strings are nothing but C arrays of Note also that, because of this thing, the size of a C string and the length of it are
two separate things: the first is the size of the array, Some people seem to think that C strings are much more efficient than /* * Containers: C String */ #include <iostream> #include <cstring> int main() { // constructor, assignment char cHeader1[]="x, f(x)"; cout<<cHeader1<<" (size="<<strlen(cHeader1)<<")\n"; /* * header1 was built with the length of the initialization string, * and the length cannot be increased. So you cannot append * more stuff to it. * What you can do is construct it with an explicit size, * guessing how much should be enough. */ char cHeader[256]="x, f(x)"; /* * assign a new value * * BEWARE, if you write * header="X, f(x)"; * you will "lose" the old memory (leak), * instead reference a new memory area * which may be shorter... */ //cHeader="X, f(x)"; // may seem to work, but don't do it!! /* * do NOT use plain strcpy,it may overwrite memory * beyond the string length */ strncpy(cHeader,"X, f(x)",sizeof(cHeader)-1); cHeader[sizeof(cHeader)-1]='/0'; // make sure it's zero-terminated /* * Append text to the string * Do NOT use plain strcat, it may overwrite memory * beyond the string length */ strncat(cHeader,", f2(x)",sizeof(cHeader)-strlen(cHeader)-1); cHeader[sizeof(cHeader)-1]='/0'; // make sure it's zero-terminated cout<<cHeader<<endl; /* * comparison * For the same reasons give above, * you must not use strcmp even to compare the whole string, * but always strncmp, like * strncmp(string,"text",sizeof(string)) */ if (strncmp(cHeader+3,"f(",2)==0) { // replace, even with a string of different length //header.replace(3,2,"Function("); // can't do this with C-string cout<<"equal\n"; } cout<<cHeader<<endl; } < C Array | Trail Index | Dynamic Memory > |