Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

i is probably supposed to be given as 1, either in the spoken part of the examination, or in a part that is missing. As written, the question is of course inapplicable since it doesn't compile.

The real point of the question is to test whether the applicant understands that array[index] is equivalent to index[array] and (presumably) why.

In C array[index] = *(array + index) = *(index + array) = index[array]. Assuming i to be 1 (otherwise behavior is undefined), 1[arr] is equivalent to arr[1] and it contains value 40.

Hmm, let's see shall we...

matilda:~ jeremyp$ cat > foo.c
int main(){

    int arr[2]={30,40};
    printf("%dn",i[arr]);
    return 0;
}
matilda:~ jeremyp$ cc foo.c
foo.c:4:5: warning: implicitly declaring library function 'printf' with type 'int (const char *, ...)'
    printf("%dn",i[arr]);
    ^
foo.c:4:5: note: please include the header <stdio.h> or explicitly provide a declaration for 'printf'
foo.c:4:18: error: use of undeclared identifier 'i'
    printf("%dn",i[arr]);
                 ^
1 warning and 1 error generated.

Yes indeed, i is undefined. You either need

int i = 1;

before that statement or it isn't an i, it's a 1. Let's try that...

matilda:~ jeremyp$ cat >foo.c
#include <stdio.h> // Stops the warning
int main(){

    int arr[2]={30,40};
    printf("%d\n",1[arr]); // Also added a \ so we get a line feed.
    return 0;
}
matilda:~ jeremyp$ cc foo.c
matilda:~ jeremyp$ ./a.out
40

That works now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top