All lessons

Working with Text

7 min · C

Work with C strings — arrays of characters terminated by \0.

C · Working with Text0/5 cleared

Enemy 1 of 5

There's no string type in C

This surprises a lot of beginners coming from other languages: C has no built-in string type. Instead, text is represented as an array of char values, with a special hidden character '\0' (the "null terminator") marking where the text ends. Every C string-handling function relies on that terminator to know when to stop reading.

A string literal like "Hello" is stored read-only by the compiler — you can look at it and copy from it, but you can't modify its characters directly. To build or change text at runtime, you declare a char array (a buffer) with enough room, and copy or append into that buffer instead.

Include <string.h> to get functions like strlen() (length) and strcat() (concatenate/append). strcat(greeting, name) appends name's characters onto the end of greeting, right up to (and replacing) greeting's terminator — which only works safely if greeting's buffer was declared with enough spare room to fit the result, as it is here with char greeting[20].

You
Packet Wolf

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: Hello, Ada