模糊性源自《标准》本身。 C99和C11对<代码>snprintf功能的描述相同。 C99的描述如下:
7.19.6.5 The snprintf
function
Synopsis
1 #include <stdio.h>
int snprintf(char * restrict s, size_t n, const char * restrict format, ...);
Description
2 The snprintf
function is equivalent to fprintf
, except that the output is written into an array (specified by argument s
) rather than to a stream. If n
is zero, nothing is written, and s
may be a null pointer. Otherwise, output characters beyond the n-1
st are
discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.
Returns
3 The snprintf
function returns the number of characters that would have been written had n
been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred. 因此,如果而且只有在被退回的价值不否定,且低于<条码>n代码>时,被完全删除的产出才算出。.
www.un.org/Depts/DGACM/index_spanish.htm 一方面, 第一句
否则,<>t>n-1<>>t/code> 以外的<>strong> 信号特性被弃置,而不是写给阵列,,在实际写成的特性末尾写成无效。
says that
if (the s
points to a 3-character-long array, and) n
is 3, then 2 characters will be written, and the characters beyond the 2nd one are discarded; then the null character is written after those 2 (and the null character will be the 3rd character written).
And this I believe answers the original question.
THE ANSWER:
If copying takes place between objects that overlap, the behavior is undefined.
If n
is 0 then nothing is written to the output
otherwise, if no encoding errors encountered, the output is ALWAYS null-terminated (regardless of whether the output fits in the output array or not; if not then some characters are discarded such that the output array is never overflown),
otherwise (if encoding errors are encountered) the output can stay non-null-terminated.
On the other hand
The last sentence
因此,如果而且只有在被退回的价值不否定,且低于<条码>n代码>时,被完全删除的产出才算出。
gives ambiguity (or my English is not good enough). I can interpret this sentence in at least two ways:
1. The output is null-terminated if and only if the returned value is nonnegative and less than n
(which means that if the returned value is not less than n
, i.e. the output (including the terminating null character) does not fit in the array, then the output is not null-terminated).
2. The output is complete (no characters have been discarded) if and only if the returned value is nonnegative and less than n
.
I believe that the interpretation 1 above contradicts THE ANSWER, causes misunderstanding and lengthy discussions. That is why the last sentence describing the snprintf
function needs a change in order to remove any ambiguity (which gives grounds for writing a Proposal to the C language Standard).
The example of non-ambiguous wording I believe can be taken from http://en.cppreference.com/w/c/io/fprintf (see 4)
), thanks to @"Martin Ba" for the link.
另见“。