What will happen when I declare like this a[a[i]]

Hi,

Can Any one explain how the following code works exactly.

#include <stdio.h>
#define N 20

int main(){
int a[N];
int i;

for(i=0;i<N;i++){
a[i]=20-i;
printf("%3d ",a[i]);
}

printf("\n\n");

for(i=0;i<N;i++){
a[i]=a[a[i]];
printf("\nvalue is%3d ",a[i]);
}

printf("\n\n");

return 0;
}

Please explain this line "a[i]=a[a[i]];" very very clearly.
Last edited on
This code ain't good. The values of the elements of a are unknown and could be anything, so the line is question is likely to access outside of the array.

Perhaps the line would be clearer if an intermediate variable was introduced:

1
2
3
4
5
6
    for (int i=0; i<N; ++i)
    {
        int index = a[i] ;
        a[i] = a[index] ;
        printf("\nvalue is %3d ", a[i]) ;
    }
now I changed code, now can you explain once...
Last edited on
Please help on this
when you print elements of the array in the first for, you will see:
20 19 18 17 16 ... 1

and then, when you do the first assignment a[i]=a[a[i]] in the second for, it's the same as if you write
a[0] = a[20] (because it takes value of zero element which is 20, and then use it as an index)

but maximal element number is 19 !!! 20th element holds unknown value
rich1@ Thanks for ur expalnation
Topic archived. No new replies allowed.