【问题标题】:Can somebody explain to me what is happening in the given code?有人可以向我解释给定代码中发生了什么吗?
【发布时间】:2013-03-28 23:18:46
【问题描述】:
   #include<stdio.h>
    int main()
    {
        char s[]="chomsky the great";
        printf("try0 %s\n",s+s[3]-s[9]);    
        printf("try1 %s\n",s+s[3]-s[1]);
        return 0;
    }   

gcc 编译器中的o/p 是

        try0 ky the great
        try1 ky the great

我无法跟踪程序在此处实际执行的操作,或者更确切地说,编译器是如何工作的。

【问题讨论】:

  • 你不明白什么?

标签: c io printf


【解决方案1】:
s+s[3]-s[9] = s + *(s+3) - *(s+9) = s + 'm'- 'h' = s + 109 - 104 =  s + 5 = s[5] 

所以 printf 从 s[5] 开始打印

printf 打印的示例:

printf("%s",s) = chomsky the great

printf("%s",s[0]) = chomsky the great

printf("%s",s[2]) = omsky the great

printf("%s",s[5]) = ky the great

【讨论】:

    【解决方案2】:

    s[3]ms[9]s[1] 都是 hm - h 是 5。s[5]k 中的 chomskys + s[3] - s[9]s + 5,它是在 chmosky 中以 k 开头的字符串。

    【讨论】:

      【解决方案3】:

      C 中的char 类型也可以视为整数类型。

      s 是指向字符串中第一个字符的指针。 s[3]-s[9] 减去第 3 位字符和第 9 位字符的 ASCII 代码并返回一些数字。

      稍后,该数字被添加到指向字符串中第一个字符 (s+s[3]-s[9]) 的指针中,并导致地址位于字符串开头后 5 个位置。

      当您将该地址传递给printf() 函数时,它会打印从该地址到字符串末尾的字符串。

      【讨论】:

      • 感谢 Johnny Mnemonic 现在我明白了!!!我在这里所做的只是尝试打印 s[m-h] 其中 m-h 返回 ascii 减法!!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      • 2021-05-26
      相关资源
      最近更新 更多