[英]Does printf %s on char *ptr deference it?
I'm not sure if there exists a similar question, but 我不确定是否存在类似的问题,但是
char *ptr = "xyz";
printf("%p\n", ptr);
prints an address, but (note the format specifiers) 打印地址,但(请注意格式说明符)
char *ptr = "xyz";
printf("%s\n", ptr);
prints the string? 打印字符串?
So far what I've learnt is that printing ptr
would give the address, and printing *ptr
would give the value. 到目前为止,我了解到的是,打印
ptr
将给出地址,而打印*ptr
将给出值。 I'm quite confused. 我很困惑
First, check about the format specifier(s). 首先,检查格式说明符。
For %s
, with fprintf()
family, from C11
, chapter §7.21.6.1 ( emphasis mine ) 对于fsff(
fprintf()
系列的%s
,来自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.如果没有
l
长度修饰符,则参数应为指向字符类型数组的初始元素的指针。 280) Characters from the array are written up to (but not including) the terminating null character.280) 将数组中的字符写到(但不包括)终止空字符。 [...]
[...]
and, for %p
, 并且,对于
%p
,
p
The argument shall be a pointer to
void
.该论点应为指向
void
的指针。 The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.指针的值以实现定义的方式转换为一系列打印字符。
So, basically, yes, when you attempt to print the content, you have to dereference the pointer (anyway). 因此,基本上,是的,当您尝试打印内容时,必须(无论如何)取消引用指针。
When you print with %s in C. You are printing an array of characters up to the first '\\0' by definition of what a string is in C. So you actually use the adress of the first character and the printf will deference it away. 在C中用%s打印时。根据C中字符串的定义,您要打印一个字符数组,直到第一个'\\ 0'。因此,实际上您使用第一个字符的地址,并且printf会尊重它远。
This means that 这意味着
char *ptr = "xyz";
printf("%s\n", ptr);
will print from the address of the ptr until the first cell from ptr where ptr[x] == '\\0'
从ptr的地址开始打印,直到ptr的第一个单元格,其中
ptr[x] == '\\0'
When using "%s"
then printf
will in essence loop over the string to print it character by character, until the string null-terminator character is found. 当使用
"%s"
printf
实际上将在字符串上循环以逐个字符地打印它,直到找到字符串的空终止符为止。
For that it needs to use array indexing, which indeed dereference the pointer. 为此,它需要使用数组索引,这实际上取消了指针的引用。
With "%s"
then printf
uses the value if where the pointer is pointing at. 如果指针指向,则
printf
使用"%s"
使用该值。 With "%p"
the value of the pointer itself is used. 用
"%p"
指针本身的值被使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.