c - 下面的表达式会输出什么,为什么?

标签 c unix

printf(&unix["\021C%set"],(unix)["Chb"]+"Trick"-0X67);

它给出的输出为“Cricket”。但我不明白为什么? http://ideone.com/fTEAHG

最佳答案

unixpredefined macro indicating it's a Unix-like system .

在 C 中,index[array] 等同于 array[index]。正如 MSDN 所解释的那样:

Usually, the value represented by postfix-expression is a pointer value, such as an array identifier, and expression is an integral value (including enumerated types). However, all that is required syntactically is that one of the expressions be of pointer type and the other be of integral type. Thus the integral value could be in the postfix-expression position and the pointer value could be in the brackets in the expression or subscript position.

所以

printf(&unix["\021C%set"],(unix)["Chb"]+"Trick"-0X67);

翻译成

printf(&"(\021C%set"[1]),"Chb"[1]+"Trick"-0X67);

&("\021C%set[1])取"\021C%set"第一个元素的地址,相当于取"C%set"的地址(由于 C 指针算法)。简化它,并重新排列一些操作数:

printf("C%set","Trick"+"Chb"[1]-0X67);

"Chb"[1]'h',也就是ASCII值0x68,所以"Chb"[1]-0X67是 1,"Trick"+1"rick"(由于 C 指针算法)。所以代码进一步简化为

printf("C%set","rick");

打印“Cricket”。

关于c - 下面的表达式会输出什么,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28994470/

相关文章:

c - 函数 main 从子例程接收到不正确的值

c - MPI_Finalize() 没有完成

bash - 重命名文件时 bash 循环的性能

c - 我如何在 C 中编写监视器代码?

c++ - 可以在没有终端的情况下在 Unix 进程上写入标准输出吗?

c - avr-ld 错误 : "gc-sections requires either an entry or an undefined symbol"

c - 在每行末尾添加新的行终止符

c++ - 如何知道要在命令行中链接的库?

unix - 将 stdout、stderr 和两者保存到 3 个单独的文件中

Bash printf 文字逐字字符串