1
#include <stdio.h>

int main()
{
    int a[] = {1, 2, 3};

    printf("%d", 0[a]);
    printf("\n%d", 2[a]);

    return 0;
}

Output:

1
3

I know how to access the array element with the index, but how this above syntax accessing the first value in both scenarios and add the prefixed numbers?

1

1 Answer 1

3

In C, the arrays and pointers have similarities. When you access an array element array[3]. This is equivalent to:

*(array + 3) // Dereferencing the 3rd index from beginning

Similarly, when you try to access it like 3[array], the statement goes like:

*(3 + array) // Identical to the first example

Which is identical. Lastly, when you want to obtain the N-th element of an array N[array], the syntax becomes:

*(N + array)

That's why you get your expected output.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.