Unusual output with printf statement

This question already has an answer here:

  • With arrays, why is it the case that a[5] == 5[a]? 17 answers

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


    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]);
    

    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, ie 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.

    链接地址: http://www.djcxy.com/p/86736.html

    上一篇: 有关指针的问题

    下一篇: 使用printf语句的不寻常输出