1
printf("%c",3["abcde"]);

How does this statement produces the output d? How the compiler executes this statement? I understand it for an int array where a[5] = 5[a] since *(a+5) = *(5+a). But here a string acts as an index other than a string name(variable name).

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
shivam mitra
  • 232
  • 1
  • 5
  • 12

4 Answers4

6

In your case

 printf("%c",3["abcde"]);

can be read as

 printf("%c","abcde"[3]);

or, as our most familiar syntax,

char p [] = "abcde";
printf("%c",p[3]);

It basically boils down to accessing the element in index 3 (C uses 0-based indexing for arrays) of the array.

This is just a syntactic-sugar for array indexing. You can use any way you like.

In case you want to dig more for better understanding, you can have a look at this question and related answers.


Note: Being Nitpicky

Your snippet is a statement, don't call it a program.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
5

The array accessor operator [] can work "both ways", so 3["abcde"] is equivalent to "abcde"[3] and index 3 (with 0 being the start) contains d.

EDIT:

The fact that we have a string constant instead of a variable doesn't matter. String constants are stored in a read-only section of memory and are implicitly typed as const char *. So the following is equivalent to what you posted:

const char *str = "abcde";
printf("%c",3[str]);
dbush
  • 205,898
  • 23
  • 218
  • 273
4

3["abcde"] is equivalent to *(3 + "abcde") and hence "abcde"[3].
When used in an expression, with some exception, "abcde" will be converted to pointer to its first element, i.e. it basically gives the base address of string "abcde".

Adding base address to 3 will give the address of 4th element of string "abcde" and therefore 3["abcde"] will give the 4th element.

haccks
  • 104,019
  • 25
  • 176
  • 264
0

Lets break this down:

printf("%c",3["abcde"]);

The printf prints the data with a certain format.

The format is %c, so the output is going to be a single character.

The character that is printing is 3["abcde"]. The "abcde" is an array of characters, and the one being accessed is the 4th letter. This is because arrays start at 0. In this case 'a' is character 0, 'b' is character 1, and on until 'e' which is 4.

To access the 'b' it would be 1["abcde"].

Note: 3["abcde"] is the same as writing "abcde"[3] and in both cases are equal to the character 'd'