If you have a character array storing a string like this
char s[ ]="Hello";
then for example the expression s[0]
yields the character 'H'
from the string.
This expression s[0]
is equivalent to the expressions 0[s]
, *( s + 0 )
, and *( 0 + s )
.
That is to output the first character of the string you can write
printf( "%c", s[0] );
or
printf( "%c", 0[s] );
or
printf( "%c", *( s + 0 ) );
or
printf( "%c", *( 0 + s ) );
And this statement from your program
printf("%c%c%c%c\t",s[i],i[s],*(s+i),*(i+s));
demonstrates all these possibilities in one statement.
From the C Standard (6.5.2.1 Array subscripting)
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).
Pay also attention to this part of the quote
A postfix expression followed by an expression in square brackets
[]...
It allows to write expressions like i++[s]
because i++
is a postfix expression.
Consider the following demonstrative program
#include <stdio.h>
int main(void)
{
char s[] = "Hello";
int i = 0;
while ( *( s + i ) )
{
printf( "%c", i++[s] );
}
putchar( '\n' );
return 0;
}
Its output is
Hello