It means that, for example, if your source string is 20 characters plus a null terminator and your strncpy
specifies less than 21 characters, the target string will not have a null appended to it.
It's because of the way it works: strncpy
guarantees that it will write exactly N bytes where N is the length value passed in.
If the length of the source string (sans null byte) is less than that, it will pad the destination area with nulls. If it's equal or greater, you won't get a null added to the destination.
That means it may not technically be a C string that you get. This can be solved with code like:
char d[11]; // Have enough room for string and null.
strncpy (d, s, 10); // Copy up to 10 bytes of string, null the rest.
d[10] = ''; // Then append null manually in case s was too long.
You allocate 11 bytes (array indexes 0..10), copy up to 10 (indexes 0..9) then set the 11th (index 10) to null.
Here's a diagram showing the three possibilities for writing various-sized strings to a 10-character area with strncpy (d, s, 10)
where .
represents a null byte:
s d
------------- ----------
Hello. Hello.....
Hello Fred. Hello Fred
Hello George. Hello Geor
Note that in the second and third case, no null byte is written so, if you treat d
as a string, you're likely to be disappointed in the outcome.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…