我不确定是否存在类似的问题,但是
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/