1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

i[a] & a[i] related..

Discussion in 'C' started by IndiraP, Nov 27, 2012.

  1. IndiraP

    IndiraP New Member

    Joined:
    Nov 10, 2012
    Messages:
    41
    Likes Received:
    2
    Trophy Points:
    0
    #include <stdio.h>
    main()
    {
    char a[5] = "abcd";
    int b = 3;

    printf("%c\n",a);
    printf("%c\n",((char *) b)[(int) a]);
    }


    i get d d as output..
    a[3] = d..i get it..

    what ((char *)b)[(int) a] doing there...
    all i can understand from the above is that it is doing something that is producing lyk i[a] from a type..
    wats happening der actually n how is it happening???
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    It's casting b, which is an integer, to a char*, then casting a, which is an array but taken as a char* in this context, to an integer, then using pointer[offset] syntax to address the 'd'.

    pointer[offset] is just worked out as pointer+offset*sizeof(*pointer) so there's no difference between a and b[a], providing b and a in the latter case are cast correctly.
     
  3. IndiraP

    IndiraP New Member

    Joined:
    Nov 10, 2012
    Messages:
    41
    Likes Received:
    2
    Trophy Points:
    0

Share This Page