请解释以下 C 程序的输出。

Please explain the output of the following C program.

Can anyone explain the working of the following code step by step?

#include<stdio.h>
main()
{
    char s[ ]="Hello";
    int i;
    for(i=0;s[i];i++)
    printf("%c%c%c%c\t",s[i],i[s],*(s+i),*(i+s));
}

I am getting the output as "HHHH eeee llll llll oooo" but I am not able to understand its working.

您有一个字符数组 "Hello"。

对于数组中的每个字符,由 i 指定的索引(直到字符 == 0 时字符串的末尾,因此为假)输出一个由以下内容组成的字符串:

  1. 当前字符(s[i])
  2. i标识的内存位置的字符+字符串开头的内存偏移量(s)
  3. 通过将索引(i)添加到字符串开头(s)的内存位置构造的指针处的字符
  4. 通过将字符串开头的内存偏移量添加到索引构造的指针处的字符。

这4次操作都指向内存中的同一个字节,因此字符重复了4次。这是一个练习,演示C语言如何直接访问内存以及如何操作指针,指针运算可以用来访问数组的内容,反过来数组变量可以用于指针运算。

如果你有一个字符数组存储这样的字符串

char s[ ]="Hello";

然后例如表达式 s[0] 从字符串中产生字符 'H'

此表达式 s[0] 等同于表达式 0[s]*( s + 0 )*( 0 + s )

也就是输出你能写的字符串的第一个字符

printf( "%c", s[0] );

printf( "%c", 0[s] );

printf( "%c", *( s + 0 ) );

printf( "%c", *( 0 + s ) );

以及您程序中的这条语句

printf("%c%c%c%c\t",s[i],i[s],*(s+i),*(i+s));

在一个陈述中展示了所有这些可能性。

来自 C 标准(6.5.2.1 数组下标)

2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

也请注意这部分引用

A postfix expression followed by an expression in square brackets []...

它允许写像 i++[s] 这样的表达式,因为 i++ 是一个后缀表达式。

考虑以下演示程序

#include <stdio.h>

int main(void) 
{
    char s[] = "Hello";

    int i = 0;

    while ( *( s + i ) )
    {
        printf( "%c", i++[s] );
    }
    putchar( '\n' );

    return 0;
}

它的输出是

Hello