2

consider following C code

int a[]={1,2,3,4};
printf("%d",2[a]);

this prints "3".How is it possible? I know in a[2] a is the base address of array.But in 2[a] what is 2? and how it accessses array a?I am totally confused with this representation of array.

WSS
  • 503
  • 5
  • 20
  • Nice catch on the duplicate, @devnull ! I have to admit I did not know the answer. – Floris Nov 20 '13 at 06:39
  • @Floris Looking at [this](http://stackoverflow.com/a/14547307/2235132), I must say that I don't believe you. – devnull Nov 20 '13 at 06:41
  • @devnull it's true: I am a self-taught hacker; as such I have occasional areas of real depth, and other complete blind spots. Which is why I hang around on this site a lot... But yeah - that was an answer I still feel pretty good about :-) – Floris Nov 20 '13 at 06:43

4 Answers4

2

There are two things to remember here:

  • The first is that array access is basically just a fancy way of using pointer arithmetic. For example, if you have the array

    int a[10];
    

    then

    a[3] = 5;
    

    is equal to

    *(a + 3) = 5;
    
  • The second thing to remember is that addition (like in a + 3 above) is commutative, so a + 3 is the same as 3 + a. This leads to e.g.

    *(3 + a) = 5;
    

    which can be interpreted as

    3[a] = 5;
    
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

int a[]={1,2,3,4}; is an integer array containing 4 elements and a is the Base Address, Let the Base Address be denoted by X . Now a[1] means element at address X + sizeOf(int) * 2 = Y (suppose) i.e. element at address Y, likewise 2[a] means element at adsress sizeOf(int) * 2 * X = Y.

Thus even if you write a[2] or 2[a] eventually complier recognizes it as Y and refres to the element at address Y which is 3 in our case.

Hope it addresses the problem right.

manish
  • 1,450
  • 8
  • 13
0
*(expr1+expr2) is equivalent to expr1[expr2] or expr2[expr1].

*(expr2+expr1) is equivalent to expr2[expr1] or expr1[expr2].
Sadique
  • 22,572
  • 7
  • 65
  • 91
0

It is just another way to write an element of an array.

In int a[]={1,2,3,4};, element at index 3 can be referenced by many methods:

  1. As an array element: a[3]
  2. Using pointer: *(a + 3) or *(3 + a) [Addition is commutative in arithmetics and in C]
  3. Now you can write the second way of representation using pointer as 3[a], i.e. a[3] is equal to *(a + 3) is equal to *(3 + a) is equal to 3[a].
0xF1
  • 6,046
  • 2
  • 27
  • 50