Main Content

Strings in C

Archive - Originally posted on "The Horse's Mouth" - 2011-01-25 04:48:24 - Graham Ellis

Strings in C are null terminated char arrays ... so you always need to allocate one more array member for them than the maximum possible length - to hold a string of up to 20 chars, you need an array of 21.

Double quoted string constants are null terminated strings, and if you assign them to a variable, you're assigning a pointer to the first character. But single quotes give you a single char variable, not an address. This means that you can compare chars using an == operator (you're comparing the characters) but you can't meaningfully compare strings with ==, and you would be comparing the addresses and would get a false return if you compared two identical strings which were held at different places in memory. Instead, you should use something like strcmp to compare strings.

There's a fresh example of some string manipulation [here], and examples of command line string handling [here] and [here]. Wrong and right ways of comparing are shown [here].

There are many aspects of C which make it more complex to learn (and slower to code in) than languages like Python and Perl, but there are times when it's the right choice - for low level coding, code that has to run many time and very efficiency, and code that must be very small. So there are time when, not withstanding the complexity, people need to learn to program with C as their target language. It's a niche requirement these days - our specialty - and so we'll welcome you if you're a newcomer to programming on our Learning to program in C course. For people who have already programmed, but need to learn / convert to C, we offer a shorter conversion course - C Programming ... I'm running it this week, and it comes up again every 2 or 3 months through the year.