0

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

2 Answers2

3

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
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

You have an array of characters "Hello".

For each character in the array, index specified by i (and until the end of the string when the character == 0 and is therefore falsey) output a string made up of:

  1. The current character (s[i])
  2. The character at the memory location identified by i + the memory offset of the start of the string (s)
  3. The character at the pointer constructed by adding the index (i) to the memory location of the start of the string (s)
  4. The character at the pointer constructed by adding the memory offset of the start of the string to the index.

These 4 manipulations all point to the same byte in memory, hence the character is repeated 4 times. This is an exercise demonstrating how the C language accesses memory directly and how pointers can be manipulated, that pointer arithmetic can be used to access the contents of arrays, and conversely that array variables can be used in pointer arithmetic.

RichGoldMD
  • 1,252
  • 1
  • 10
  • 18