0
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?

Identicon
  • 1
  • 1
  • 2
    See https://stackoverflow.com/q/381542/1216776 – stark May 01 '20 at 13:08
  • It loops 3 times on ideone... https://ideone.com/9J4czQ – pmg May 01 '20 at 13:08
  • Asking about the loop operation is a separate question from the subscript issue and ought to be asked in a separately posed question. However, the middle expression of the `for`, `s[i]` causes the loop to continue if and only iff it is not zero. Since `s[i]` is referring to the elements of the string, it has the values `'m'` (which is not zero) in the first iteration, `'a'` in the second (still not zero), `'n'` in the third (also not zero), and `'\0'` in the fourth. This last value is zero, so the fourth iteration is not executed. There is a `'\0'` in the string because `"man"` puts one there. – Eric Postpischil May 01 '20 at 13:15

1 Answers1

0

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].

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312