c - printf %s on char *ptr 是否遵循它?

标签 c printf

我不确定是否存在类似的问题,但是

char *ptr = "xyz";
printf("%p\n", ptr);

打印地址,但是 (注意格式说明符)

char *ptr = "xyz";
printf("%s\n", ptr);

打印字符串?

到目前为止,我了解到打印 ptr 将给出地址,而打印 *ptr 将给出值。 我很困惑。

最佳答案

首先,检查格式说明符。

对于 %s,使用 fprintf() 系列,来自 C11,第 §7.21.6.1 章(强调我的)

s

If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type.280) Characters from the array are written up to (but not including) the terminating null character. [...]

并且,对于 %p

p

The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

所以,基本上,是的,当您尝试打印内容时,您必须取消引用指针(无论如何)。

关于c - printf %s on char *ptr 是否遵循它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51363236/

相关文章:

c - 如何在 C 中同时打印两个函数?

c - 编写一个程序(用 C 语言)打印所有超过 10 个字符的输入行

c - 如何根据 long 的大小更改我的 sprintf 格式字符串

c - 带有 "return"语句的多行宏函数

c - 算术溢出是否等同于模运算?

c++ - dlopen 或 dlclose 未调用信号处理程序

c - 如何使用省略号 (...)

c - %c 与 %s 的实际差异

c - inet_pton() 给出 "Segmentation fault"

c - C中的printf()和puts()有什么区别?