Tag: strings

Tutorial 14 on working with strings published

Tutorial 14 on working with strings published

Code listing on screen with keyboard
Image by Markus Spiske from Pixabay

Reading the C reddit most days, I see from time to time question about strings. They’re not particularly complex but I feel you really have to get your head around pointers to grok strings. I’ve already done a C tutorial on Pointers and c-strings but I thought showing some examples of doing things with c-strings would not go amiss.

The pointers aspect of C strings probably muddies the water a bit. All you are doing is manipulating a contiguous block of characters in RAM that ends with a 0. The pointer just tells you where in RAM that block begins. So long as it finishes with a 0 (\0 in C), it will work ok.

That’s what Tutorial 14- working with strings is about.  Especially for beginners, doing things like converting ints to strings, or concatenating strings can be a bit fiddly. I’ve also provided both the Windows and Linux versions. i.e. compiling with Visual C on Windows and clang on Ubuntu.

For instance, you might have heard about the long to ascii function ltoa. Bad news. It doesn’t exist in Linux compilers.  There is a Windows version with the instantly memorable (not) name _ltoa_s, which is one of the safe C functions.  Incidentally if you are using SDL then there is a SDL_ltoa function provided for you although oddly it’s not documented.

Improving on C strings

Improving on C strings

Image by Anja🤗#helpinghands #solidarity#stays healthy🙏 from Pixabay

Although C has many useful features, Text or string handling is not one of them. Unless you are writing text adventures, this is probably not a big deal and even games like Asteroids do write text messages, show the score etc.

Givn C’s age, it’s not surprising that people have tried to improve on C’s strings (char *) and one that I came across is the Better string library. The library is stand alone, portable and known to work with gcc/g++, MSVC++, Intel C++, WATCOM C/C++, Turbo C, Borland C++, IBM’s native CC compiler on Windows, Linux and Mac OS X. If you are bothered by buffer overflow type bugs, this is one area that BSL can definitely improve on. Note although the main documentation is just one text file, it is a very long file!

I haven’t tested it with clang but if it works with gcc the odds are it will work with clang.

I’ve added it to the C code links page.