C strings – part II

In the last post, the one talking about C strings, I promised a sequel about common problems when doing seemingly innocent operations with them, so here it is.
The list is by no means complete. It is actually very short, just 3 or 4 points. If you care to add more, feel free.

Overlapping strings

When talking about operations with C strings, particularly strcat and strcpy, I mentioned these should not be used with overlapping strings. In case the reasons were not evident enough, we’ll look at some examples. Keep in mind how these functions work, that is the fact that they rely only on the terminating '' character for determining where a string ends.
Now let’s see a small piece of code: Continue reading C strings – part II

C Strings

First and most important of all regarding C strings is this: there is no such thing as C strings.

OK, now that that’s out of the way we can move on. The way to work with strings in C is to treat them as simple sequences of characters, a.k.a. a string in C is stored as an array of char’s. To know where the string ends, it must be terminated by a special marker, which is the ASCII character with the code 0 (commonly known as ‘’) – this is why they’re called zero-terminated C strings (we’ll see later that there are alternatives to this). Let’s see an example:
[code lang=”c”]char myString[100];

myString[0] = ‘h’;
myString[1] = ‘e’;
myString[2] = ‘l’;
myString[3] = ‘l’;
myString[4] = ‘o’;
myString[5] = ‘\0’; /* don’t forget the marker */[/code]
If you want to do the memory allocation stuff by hand, you would just change the declaration for myString to this:
[code lang=”c”]char *myString = NULL;
myString = (char *)malloc(100 * sizeof(char));[/code]
Just creating a string and putting some characters inside isn’t such a big deal. You have to be able to do all sorts of stuff with it for this to be useful, things like copy them around, splitting them up (getting sub-strings from a bigger string), putting them back together (concatenating two strings into a single one), searching for things inside them. Fortunately, the creators of the C standard library thought of us and provided functions that do all of these things and more. All you have to do to use them is:
[code lang=”c”]#include <string.h>[/code]
We’ll look in detail at some of these functions and, in the spirit of learning by doing, we’ll also try to provide our own implementations for them. Continue reading C Strings