int main(){
int arr[2]={30,40};
printf("%dn",i[arr]);
return 0;
}
I found this question in an examination and the given solution is 40
But I think it should give an error since i is undefined. Or, may be I am missing something. Please explain me how 40 is the correct answer?
Thanks in advance.
You are correct, the code is wrong. Likely, it is a typo, and the intent was either to define i
or to use 1[arr]
.
Probably it is an error, since i
is not defined.
Also, probably the intention of the exercise is to take advantage of the fact that in C, you can write v[ i ]
in order to access the #i element of a vector v, or i[ v ]
.
Both forms are equivalent.Since v[ i ]
is translated as *( v + i )
, there is actually not any difference between that and *( i + v )
, which is what i[ v ]
is translated for. This is not a common use, but is nonetheless valid.
Arrays in C, from Wikipedia
In this specific example, 1[arr]
would return the expected answer.
I just wonder why they chose 40 instead of 42.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With