-1

While I was learning Strings in C I came across the following piece of code

#include <stdio.h>

int main()
{
    char str[15] = "Hello, World";

    printf("str[0] = %c\n", str[0]);
    printf("*(str + 0) = %c\n", *(str + 0));
    printf("*(0 + str) = %c\n", *(0 + str));
    printf("0[str] = %c\n", 0[str]); /* This line 0[str] */

    return 0;
}

Simple things what I can figured out from the program are

str[0] will produce H
*(str + 0) will also produce H as it uses pointer arithmetic
*(0 + str) is similar to *(str + 0) and will also produce H

What I can't figure out is what does 0[str] means and how does it evaluates to H. As what I have learnt is [ ] symbol represents an array and 0 is not an array.

Pankaj Prakash
  • 2,300
  • 30
  • 31
  • Although this is a duplicate - when viewed from that angle - what is the purpose of a `+0`? Or is that jut an unfortunate value? – user2864740 Aug 11 '15 at 06:56

1 Answers1

2

consder the code below,

char str[10];

str will return the starting address address of the array str[10].

So in your example *(str + i) will return the element str[i].

str[i] = i[str] because addition is commutative. Since *(str + i) and *(i + str) are equal because i + str = str + i.

Specifically 0[str] = str[0] because *(str+0) = *(0+str). Because str+0 = 0+str =str.

Deepu
  • 7,592
  • 4
  • 25
  • 47