In my last post, I discussed some stuff about C-strings and working with them in C++. Today I'm elaborating a bit, talking about my most frequently made mistake and some other cool functions you can use. Remember to include the <cstring> library when working with functions on these C-strings!
Using assignment and comparison operators
someString = "Hey!";
This is illegal! Using the assignment operator with a C-string is an initialisation, not assignment. Remember, C-strings behave like arrays and have their own member functions. Assigning a value to the variable when you declare it, is however legal:
char someString = "Legal!";
To correctly assign characters to this variable if you don't know its value at declaration, you should use the strncpy() function:
strncpy(someString, 'Foo', 9);
This function takes 3 parameters, the original declared character string, the new string to be copied to the string and the maximum number of characters to copy, leaving space for the null character (discussed in my previous post about C-strings). You can use the strcpy() function as well, but this does not provide a safeguard against accidentally discarding the null character. This is not implemented in all versions of C++.
Sometimes you need to check the equality of C-strings, but using the equality operator ( == ) will yield strange, unexpected results. Luckily for us, we have another handy function at our disposal:
This one is a bit weird. It takes two strings as parameters. If str1 is equal to str2, then the function returns 0. If not, it returns a positive value or a negative value. It has to do with the lexicographic order of the characters in the two strings.
Be careful not to copy characters beyond the end of a C-string using strcpy. I've done this accidentally and it yielded really confusing results in some of my practice programs. If you do this, the function will crash your program or open your system to malicious attacks. Apparently it has been such a serious problem, some compilers refuse to compile the code until you override the warning. A safer way to prevent programmers, especially new ones from making really bad mistakes!
Anyway, this is just a short post about thoughts and things I need to keep in mind while working with C-strings. Luckily a <string> data type exists and makes working with strings slightly easier!