C 程序所需的解释
在我买的一本c书中,给出了一个锻炼计划:
以下代码片段的输出是什么?
printf(3+"Welcome"+2);
我得到的答案是我(通过在 TC++ 中执行它)
但我无法获得实际的机制。 请解释一下其背后的实际机制。
In a c-book I bought, an exercise program is given as
what is the output for the following code snippet?
printf(3+"Welcome"+2);
the answer I got is me (by executing it in TC++)
But I can't get the actual mechanism.
please explain me the actual mechanism behind it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这称为指针算术:2+3=5,“me”是从偏移量 5 开始的字符串的其余部分
。PS:扔掉那本书。
It's called pointer arithmetic: 2+3=5, and "me" is the rest of the string starting at offset 5.
PS: throw away that book.
编译后,“Welcome”字符串将变为
const char *
,指向该字符串的第一个字符。在 C 中,使用字符串(就像任何指针一样),您可以进行指针算术。这意味着指针 + 5 指向指针之外的 5 个位置。因此 ("Welcome" + 5) 会将“W”后面的 5 个字符指向子字符串“me”。
顺便说一句,正如其他人所建议的那样,这听起来不像一本好书。
When this is compiled the "Welcome" string becomes a
const char *
, pointing to the first character of the string. In C, with character strings (like any pointer), you can do pointer arithmetic. This means pointer + 5 points to 5 places beyond pointer.Therefore ("Welcome" + 5) will point 5 characters past the "W", to the substring "me."
On a side note, as other have suggested, this doesn't sound like a good book.
字符串(如
"Welcome"
)是一个以 NUL 字符结尾的字符数组(因此它实际上是"Welcome\0"
)。您正在做的是访问它的第五个字符(3 + 2 = 5)。该字符是
'm'
(数组索引从0开始)。printf
将继续读取,直到遇到 NUL 字符。A string (like
"Welcome"
) is an array of characters terminated by the NUL-character (so it's actually"Welcome\0"
).What you are doing, is accessing the fifth character of it (3 + 2 = 5). This character is
'm'
(array indices start at 0).printf
will continue to read till it hits the NUL-character.