char s[]="man";
int i;
for(i=0;s[i];i++)
printf("%c%c%c",i[s],*(i+s),*(s+i));
The code might look simple but as a beginner I wasn't able to understand how i[s]
gives the output. And how *(i+s)
was giving output as n?
char s[]="man";
int i;
for(i=0;s[i];i++)
printf("%c%c%c",i[s],*(i+s),*(s+i));
The code might look simple but as a beginner I wasn't able to understand how i[s]
gives the output. And how *(i+s)
was giving output as n?
In C, for expressions E1
and E2
, the subscript operation E1[E2]
is defined to be *((E1)+(E2))
, which means to add E1
and E2
and use the resulting pointer to access an object.
Most often, E1
is a pointer, and E2
is an integer, and (E1)+(E2)
adds the integer to the pointer by producing a pointer that is E2
elements further along in memory than where E1
points. However, addition is commutative, so (E2)+(E1)
is the same as (E1)+(E2)
. Due to the definition of the subscript operation, this means you can write E2[E1]
with the same effect.
Note that the subscript operator works only with one pointer and one integer. If you provide an array, it is automatically converted to a pointer to its first element. This conversion occurs before the subscript operator is applied. Thus, if you have int array[4]
, then array[2]
is automatically converted to p[2]
, where p
is a pointer with the value &array[0]
, the address of the first element of array
.
Similarly, if you write 2[array]
, then array
is again converted to that p
, and the result is 2[p]
. By definition, that is *(2+p)
, so the result is adding 2 to p
and then referencing the memory that points to, which is the element array[2]
.