gpt4 book ai didi

c - C语言中printf和printf_s有什么区别?

转载 作者:行者123 更新时间:2023-11-30 21:38:29 30 4
gpt4 key购买 nike

我只是想知道其中的区别,并且我已经尝试过在 Google 上进行搜索。

printf()printf_s()

最佳答案

今天我学到了一些新东西。我从未使用过 _s 函数,并且始终假设它们是供应商提供的扩展,但它们实际上是在附件 K“边界检查接口(interface)”下的语言标准中定义的。关于printf_s:

K.3.5.3.3 The printf_s function

Synopsis

1 #define _ _STDC_WANT_LIB_EXT1_ _ 1
#include <stdio.h>
int printf_s(const char * restrict format, ...);
Runtime-constraints

2 <strong>format</strong> shall not be a null pointer. The %n specifier 394) (modified or not by flags, fieldwidth, or precision) shall not appear in the string pointed to by <strong>format</strong>. Any argumentto <strong>printf_s</strong> corresponding to a <strong>%s</strong> specifier shall not be a null pointer.

3 If there is a runtime-constraint violation, the printf_s function does not attempt toproduce further output, and it is unspecified to what extent <strong>printf_s</strong> produced outputbefore discovering the runtime-constraint violation.

Description

4 The printf_s function is equivalent to the printf function except for the explicitruntime-constraints listed above.

Returns

5 The printf_s function returns the number of characters transmitted, or a negativevalue if an output error, encoding error, or runtime-constraint violation occurred.
394) It is not a runtime-constraint violation for the characters %n to appear in sequence in the string pointedat by format when those characters are not a interpreted as a %n specifier. For example, if the entireformat string was %%n.

C 2011 Online Draft

总而言之,printf_sprintf 未完成的参数执行额外的运行时验证,并且如果任何运行时验证失败,则不会尝试继续。

_s 函数是可选,编译器不需要支持它们。如果它们受支持,则宏 __STDC_WANT_LIB_EXT1__ 将被定义为 1,因此如果您想使用它们,您需要像

#if __STDC_WANT_LIB_EXT1__ == 1
printf_s( "%s", "This is a test\n" );
#else
printf( "%s", "This is a test\n" );
#endif

关于c - C语言中printf和printf_s有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55634311/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com