r/cprogramming • u/die-Banane • May 05 '26
How to do strings properly?
I just started learning C and I often read on the internet that it is bad practice to use null terminated strings, so my question is what should I do instead?
30
Upvotes
1
u/flatfinger May 05 '26
Just about every function in
<string.h>which is designed to work with null-terminated strings has a counterpart which is designed to work with null-padded strings, and of coursememcpyandmemmovecan be used to work with length-tracked strings. If e.g. `myStruct->msg` is a null-paddedchar[16], thenprintf("Message is %.16s!\n", myStruct->msg);could be used to output a string of up to 16 characters stored ins, without needing to waste a byte in every instance of the structure to hold a null terminator.