Why is a[1] == 1[a] in the C array?

Asked 2 years ago, Updated 2 years ago, 122 views

It's a code that my friend sent me, saying she found a weird function 1[a] It compiles well and executes well. What's going on here?

int main(){
    int* a = (int*)malloc(sizeof(int)*2);
    a[0] = 1;
    a[1] = 2;
    printf("%d\n", a[1]);
    printf("%d\n", 1[a]);//????????
}

c array pointer-arithmetic pointer

2022-09-22 22:21

1 Answers

The [] operator definition of the C standard is a[b] == *(a + b) This is.

That is, in this case

It is calculated as . Addition is (a+1) = (1+a) because the exchange law is established, Therefore, since the calculation results for these two are the same, finding the address value will result in the same result.


2022-09-22 22:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.