printf语句间$ P $如何PTED? [英] How is printf statement interpreted?
问题描述
如何以下行间$ P $由GCC编译器PTED:
How is the following line interpreted by GCC compiler:
printf("HELLO");
我想知道这是因为当我运行下面的程序:
I want to know this because when I am running following program:
main()
{
printf(5+"Good Morning");
}
该计划是打印:
Morning
为什么编译器会从第6个字符开始打印?
Why is the compiler is starting the printing from the sixth character?
推荐答案
有这里发生了很多事情。正如其他人所说,的printf()
不'知道'对前pression 5+早上好什么
。即前pression的价值是由C语言决定。
There are a lot of things happening here. As others have said, printf()
doesn't 'know' anything about the expression 5+"Good Morning"
. The value of that expression is determined by the C language.
首先, A + B
相同 B + A
,所以 5 +早上好
相同早上好+5
。
First, a+b
is the same as b+a
, so 5+"Good Morning"
is the same as "Good Morning"+5
.
现在,早上好的类型
(即一个字符串)是一个阵列字符
。具体来说,早上好
是一个13字符数组(12常规字,随后 0
) 。当大多数前pressions使用时,输入C数组衰变的指针到它的第一要素,二进制加法就是这样的一个情况。这一切都意味着,在早上好+5
,早上好
衰变到一个指向它的第一个元素,这是字符
Now, the type of "Good Morning"
(i.e., a string literal) is an "array of char
". Specifically, "Good Morning"
is a 13-character array (12 "regular" characters, followed by a 0
). When used in most expressions, the type of an array in C "decays" to a pointer to its first element, and binary addition is one such case. All this means that in "Good Morning"+5
, "Good Morning"
decays to a pointer to its first element, which is the character G
.
下面是内存的样子:
0 1 2 3 4 5 6 7 8 9 0 1 2
+---+---+---+---+---+---+---+---+---+---+---+---+---+
| G | o | o | d | | M | o | r | n | i | n | g | 0 |
+---+---+---+---+---+---+---+---+---+---+---+---+---+
M
。因此,的printf()
越来越即在 M
的地址。即,直到它找到一个 0
的printf()
打印。因此,你看到晨
作为输出。
The value of the address of G
plus 5 is a pointer that points to 5 locations from G
above, which is M
. So, printf()
is getting an address that is at M
. printf()
prints that till it finds a 0
. Hence you see Morning
as output.
这篇关于printf语句间$ P $如何PTED?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!