gpt4 book ai didi

c - printf(3 +"excellent"+4) 这行代码如何运行?

转载 作者:行者123 更新时间:2023-12-03 01:54:41 25 4
gpt4 key购买 nike

我不明白为什么这个程序的输出是nt
谁能解释一下这个程序吗?

#include <stdio.h>
#include <stdlib.h>

int main(){

printf(3+"excellent"+4); //output is "nt"

return 0;
}

最佳答案

"excellent"char[10] 类型的数组,其元素是单词的 9 个字母和终止符 '\0 '。然后,C11 6.3.2.1p3 ,

  1. Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue. [...]

即它被转换为指向字符串第一个字符 (e) 的指针,然后具有类型 char *

现在我们添加了两个内容:

(3 + (char *)"excellent") + 4

C 标准规定(简化为 C11 6.5.6p8 ),当将整数和指针相加时,结果将是相同类型的指针,并且将被解释为如果指针 p 指向数组的元素 n,那么 p + m 将产生一个指向数组元素 n + m 的指针同一数组,或超过末尾,或者,如果 n + m 超出数组范围或超过末尾,则行为未定义。

3 + "excellent" 将给出一个指向 excellent 的第二个字母 e 的指针。当然,由于带括号的表达式的类型为 char * 并且它指向数组的元素 3,如果我们向它添加 4,我们会得到一个指向元素 7 的指针,即第 8 个字母,n

 <-------------- char [10] -------------->

+---+---+---+---+---+---+---+---+---+---+
| e | x | c | e | l | l | e | n | t | \0|
+---+---+---+---+---+---+---+---+---+---+
^ ^ ^
|  | |
first character, "excellent" after lvalue conversion
| |
+ 3 + "excellent"
|
+ 3 + "excellent" + 4

现在最后,当我们调用 printf 并将这样的指针作为参数时会发生什么? printf 会将参数视为指向空终止字符串(即格式字符串)的第一个字符的指针。除了以 % 开头的特殊序列之外,所有字符都将逐字复制到输出,直到满足终止 null。

<小时/>

研究这些问题的另一种方法是记住这一点

*(a + b)

等于

a[b] (or even b[a])

并且由于 &*x 相当于 x

&*(a + b) == (a + b) == (b + a) == &a[b] == &b[a]`

我们明白了

3 + "excellent" + 4

等于

&"excellent"[3] + 4

等于

&"excellent"[3 + 4]

&"excellent"[7]

关于c - printf(3 +"excellent"+4) 这行代码如何运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58982070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com