689 views
0 votes
0 votes
For arrays with more given elements than its size, why does doing a[i] print garbage value but *a+i brings the correct value, despite them being the same thing (a[i] = *a+i)

int a[2] = {1,2,3,4};

for ( int i =0 ; i<=4 ;i++){

 printf(“%d” , a[i];        // gives 1, 2, Garbage , Garbage

 printf(“%d”, *a+i;       // gives 1, 2, 3, 4

}

1 Answer

Best answer
4 votes
4 votes
In the second printf(), you are first de-referencing a and then adding i to it, i.e. you are fetching a[0] (=1) and then adding i to it in every iteration. This is why you are getting 1, 2, 3, 4, 5.

You should note that, a[i] $=$ *(a + i) $\neq$ *a + i. Precedence of * (de-reference operator) is higher than the arithmetic operator $+$.

If you use *(a + i) in the second printf() then you will get similar output for both print statements.
edited by

Related questions

1 votes
1 votes
2 answers
2
0 votes
0 votes
1 answer
3
Gurdeep Saini asked Feb 1, 2019
655 views
is it dangling pointer ?int main(void) { int* p;printf("%d",*p); return 0;} https://ideone.com/IN77el
0 votes
0 votes
0 answers
4
gmrishikumar asked Jan 2, 2019
854 views
#include<stdio.h>int main ( ){ int demo ( ); // What is this and what does it do? demo ( ); (*demo) ( );}int demo ( ){ printf("Morning");}