解释下面的代码片段的输出是什么? [英] Explain the output of the following snippet?

查看:186
本文介绍了解释下面的代码片段的输出是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有鉴于此code

 的char * s =阿巴斯;
的printf(%S,S + S [1] - S [3]);

为什么会出现这种输出?

  BBAS


解决方案

 的char * s =阿巴斯;
S + S [1] - S [3]
S +'B' - '一'
S + 1 / *假设ASCII编码。 Posibly在那里你测试的机器,(S +'B') - 'A'= S + 1 * /
BBAS

要更好地理解打印以下值

 的printf(%C(%D),%C(%D),%C  - %C =%d个\\ N,
    / * ^ ^ ^ ^ ^ ^ ^ * /
      S [1],S [1],S [3],S [3],S [3],S [1],S [3] - S [1]);
的printf(%S - %S - %的,S,S + 1,S + 2);

内存布​​局

  + ----- + ----- + ----- + ----- + ----- + ----- +
| 'A'| 'B'| 'B'| 'A'| 'S'| '\\ 0'|
+ ----- + ----- + ----- + ----- + ----- + ----- +
   šš+ 1 S + 2 S + 3 S + 4秒+ 5


修改

正如在其他的答案和评论中指出, S + S [1] -s [3] 导致UB。为了确保你得到 BBAS 在输出时,你应该使用parantesis左右后前pression: S +(S [1] -s [3 ])

Given this code

char *s = "Abbas";
printf("%s", s + s[1] - s[3]);

Why is this the output?

bbas

解决方案

char *s = "Abbas";
s + s[1] - s[3]
s + 'b' - 'a'
s + 1 /* Assuming ascii encoding. Posibly the machine where you tested, (s + 'b') - 'a' = s + 1 */
"bbas"

To understand better print the following values

printf("%c (%d), %c (%d),   %c - %c = %d\n",
    /*   ^   ^    ^   ^      ^    ^    ^ */
      s[1],s[1],s[3],s[3], s[3], s[1],s[3] - s[1]);
printf("%s - %s - %s", s, s+1, s+2);

Memory layout

+-----+-----+-----+-----+-----+-----+
| 'A' | 'b' | 'b' | 'a' | 's' | '\0'|
+-----+-----+-----+-----+-----+-----+
   s    s+1   s+2   s+3   s+4   s+5


EDIT

As noted in other answer and comments, s+s[1]-s[3] leads to UB. To make sure you get bbas in output, you should use parantesis around later expression: s+(s[1]-s[3])

这篇关于解释下面的代码片段的输出是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆