Strings buffers and pointers in C

In C Strings can be generally initalized as

char *str = "string";  


char str[] = "string";  

You can usually switch between array subscript and pointer dereferencing, but there are a couple points to consider.

String buffers

Continuing with the examples from above, *str is a pointer to a string literal, whereas str[] is a buffer initialized to a string.

The difference is that string literals will be prefixed with const keyword, so they're immutable. Unfortunately, this isn't always treated as a compile time warning, and Clang will allow you to try manipulating *str all the way up to the segfault.

Pointer arithmetic

Pointer arithmetic works well for iterating through a string, as you don't have to keep a separate iterator. Keeping track of your iterator may not sound like much, but 42's style guide Norminette
[pdf] has a strict line count, and forbids all loop constructs except while (e.g., for).

However, iterating through the characters of a string has some side effects when you're planning on returning the string or modifying in place. After incrementing str++ to the end of str, the pointer is likely not where the caller expects it to be.

String Buffers vs. Pointers

This subtle difference has caught me off guard for longer than I care to admit since most of my programming is done in languages that don't hate me. Now I'll remember that buffers are for mutating, and pointers are for clean and terse interaction.


Read more posts by this author.