6 ms·
Imho its pretty simple: Strings in C are 0-terminated char arrays. If the char array is not 0-terminated, its not a string. strncpy() can make a string into a
by dobin 3y ago
Imho its pretty simple: Strings in C are 0-terminated char arrays. If the char array is not 0-terminated, its not a string.
strncpy() can make a string into a non-string (depending on size), which is clearly bad.
- alcover 3y ago> Strings in C are 0-terminated char arrays To be pedantic, they're pointers to char. Nothing more. Calling them array confuses non-C coders. The length is just an unenforced contract and has to be passed.
- TillE 3y agoIt's a pointer to a chunk of memory which contains an array of characters. You pass around the pointer because copying an array is expensive and wasteful. I think (or hope) the concepts are pretty clear if you understand what a pointer is.
- masklinn 3y agoThat’s because strncpy does not return a nul-terminated (“C”) strings, but a fixed-size nul-padded strings. That, as it turns out, is the case of most (but not all) strn* functions. Of course strncpy adds the injury that it’s specified to alllow nul-terminated inputs (it stops at the first nul byte, before filling the target buffer with nuls).
- lelanthran 3y agoIt also, in some situations, returns a *string" that doesn't have the null terminator, which means it is giving the caller something that literally isn't a string.
- masklinn 3y agoIt always “returns” the same thing: a fixed size nul-padded buffer. Call it a char array if you want, that’s always been it’s role and contract.
- dundarious 3y agostrncpy isn't good either. But using length delimited strings is the best way to generate fixed length char strings and NUL terminated strings.
- Dwedit 3y agostrncpy was a bad mistake. If you know the length and there's no null termination, you use memcpy instead.