简体   繁体   English

C程序需要的解释

[英]needed explanation for a c-program

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++) 我得到的答案是我(通过在TC ++中执行)

But I can't get the actual mechanism. 但是我无法获得实际的机制。 please explain me the actual mechanism behind it. 请向我解释其背后的实际机制。

It's called pointer arithmetic: 2+3=5, and "me" is the rest of the string starting at offset 5. 这称为指针算术:2 + 3 = 5,“ me”是字符串中从偏移量5开始的其余部分。

PS: throw away that book. PS:扔掉那本书。

When this is compiled the "Welcome" string becomes a const char * , pointing to the first character of the string. 编译后,“ Welcome”字符串变成const char * ,指向字符串的第一个字符。 In C, with character strings (like any pointer), you can do pointer arithmetic. 在C中,可以使用字符串(如任何指针)进行指针算术运算。 This means pointer + 5 points to 5 places beyond pointer. 这意味着指针+ 5指向指针之外的5个位置。

Therefore ("Welcome" + 5) will point 5 characters past the "W", to the substring "me." 因此(“ Welcome” + 5)会将“ W”后面的5个字符指向子字符串“ me”。

On a side note, as other have suggested, this doesn't sound like a good book. 顺便提一句,正如其他人所建议的那样,这听起来并不像一本好书。

A string (like "Welcome" ) is an array of characters terminated by the NUL-character (so it's actually "Welcome\\0" ). 字符串(如"Welcome" )是由NUL字符终止的字符数组(因此实际上是"Welcome\\0" )。

What you are doing, is accessing the fifth character of it (3 + 2 = 5). 您正在执行的操作是访问它的第五个字符(3 + 2 = 5)。 This character is 'm' (array indices start at 0). 此字符为'm' (数组索引从0开始)。

printf will continue to read till it hits the NUL-character. printf将继续读取,直到达到NUL字符为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM