Working with C-strings in C++ - Part 2

Published on 23 Aug 2020

In my last post about working with C-strings in C++, 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 library when working with functions on these C-strings!

Using assignment and comparison operators

Assignment This was tricky for me at first, because I am used to working with Javascript and it's wacky dynamic typing made me a bit too comfortable. C-strings are not like other data types, so you cannot simply do this:

char someString[10];
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[10] = "Legal!";

To correctly assign characters to this variable if you don't know its value at declaration, you should use the strncpy() function:

char someString[10];
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++.

Comparison 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:

strcmp(str1, str2)

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 data type exists and makes working with strings slightly easier!