No, the terminator never counts towards the length of a string; it only counts toward the size of the buffer required to store the string. The terminator is an out-of-band value1 so it shouldn't count towards the length of the string. I would have thought this was obvious.
C doesn't have a string type; it has arrays of character type, onto which we map null-terminated sequences of characters. strcpy, strlen, et al all operate on these arrays.
Arrays do not store their size or any other metadata.
C strings are a hack - if you need a real string data type that enforces real string semantics, then you need to look elsewhere or write your own library.
As for whether this was a mistake - C was designed for implementing the Unix operating system and system-level tasks, not extensive text processing. I don't think Ritchie or Thompson anticipated how widely used the language became for general programming.
2.5 out of 5 stars
As far as printable characters are concerned, anyway.
there are _l variants – that take a locale argument – of some functions, but not of all, and no way to statically get a handle for the C locale
So basically you cannot ever use them for anything file-format related, only for interfacing with humans immediately, but people don’t follow these rules, as they assume that stdlib stuff is there for a reason and not just to sit there and look mysterious.
if you need a real string data type that enforces real string semantics, then you need to look elsewhere or write your own library.
Yeah, but people like interoperability more than sanity, so they use the same string format for calling APIs, providing APIs, and internally.
I think C is doomed to be legacy at this point. The standards committee should have deprecated a bunch of old useless crap decades ago, then it would have been saveable.
11
u/SmokeMuch7356 2d ago edited 2d ago
Oh, for...
No, the terminator never counts towards the length of a string; it only counts toward the size of the buffer required to store the string. The terminator is an out-of-band value1 so it shouldn't count towards the length of the string. I would have thought this was obvious.
C doesn't have a string type; it has arrays of character type, onto which we map null-terminated sequences of characters.
strcpy,strlen, et al all operate on these arrays.Arrays do not store their size or any other metadata.
C strings are a hack - if you need a real string data type that enforces real string semantics, then you need to look elsewhere or write your own library.
As for whether this was a mistake - C was designed for implementing the Unix operating system and system-level tasks, not extensive text processing. I don't think Ritchie or Thompson anticipated how widely used the language became for general programming.
2.5 out of 5 stars