Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C concepts on arrays [closed]

Tags:

arrays

c

output

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.

like image 605
Utkal Sinha Avatar asked Jan 09 '14 16:01

Utkal Sinha


2 Answers

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].

like image 163
Eric Postpischil Avatar answered Oct 15 '22 17:10

Eric Postpischil


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.

like image 45
Baltasarq Avatar answered Oct 15 '22 19:10

Baltasarq