Array indexing error?

Two students A and B were given an assignment to write a C code in which an int array a of 5 elements is declared/initialized with {1,2,3,4,5} at compile-time and the 2nd element (0-indexing) of a is printed in output (stdout).

Given below are the code snippets written by A and B respectively.

Code by A:

1
2
3
4
5
6
#include<stdio.h>
int main() {
    int a[5]={1,2,3,4,5};
    printf("%d",2[a]);
    return 0;
}

Code by B:

1
2
3
4
5
6
#include<stdio.h>
int main() {
    int a[5]={1,2,3,4,5};
    printf("%d",a[2]);
    return 0;
}

Which of the two code snippets are correct (they give the desired output without any errors) ?

B is correct but A gives compile-time error B is correct but A gives run-time error Both A and B give compile-time error Both A and B are correct. Both A and B give run-time error

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

In C, both a[2] and 2[a] are the same... This has relation to the address of the array(It references to a particular position of the continuous memory allocation) and its pointer variable

It'd be better if you elaborate what that "relation" is.

Hint: What does a[2] and 2[a] mean in pointer arithmetic notation? How are they same?

Prasun Biswas - 4 years, 11 months ago

Is it applicable only for c language

Ritu Roy - 4 years, 11 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...