3 ms·
It always boggles me why people went with null-terminated strings in C instead of just putting the length of the string in the first 4 bytes and then the string
by dheera 5y ago
It always boggles me why people went with null-terminated strings in C instead of just putting the length of the string in the first 4 bytes and then the string after that.
And just generally doing that for all arrays. That way if you're passed ONLY a pointer to the array, you can always tell how long it is without requiring the caller to tell you how long it is, which seems to be a common theme among C functions. And that also allows your string to contain null characters, which is useful in many circumstances.
- saagarjha 5y agoBecause this is how strings in C have always been done and this is how the language and pretty much all libraries treat strings.
- WalterBright 5y agoEmbedding the length means you cannot slice strings. To get a substring one has to reallocate. Of course, null termination also means that slicing is restricted to being a tail.