Nexabion Interview Question
Developer Program Engineerspretty good q to understand the stack...if following printf() prints same addr(for a[5] & i) then u will go in infinite loop..
int
main()
{
int i=0;
int array[5];
printf("addr a[5]:%p i:%p\n", &array[5], &i);
for(i=0;i<=5;i++)
array[i]=0;
printf("why this printf not working?");
return 0;
}
I still didn't understand why the address of i is the same as the address of array[5]? Even if you switch the order of the variable declarations from
int i=0;
int array[5];
to
int array[5];
int i=0;
, it seems to have the same behavior.
This is strictly compiler dependent I feel. This is the behavior under gcc.
Anybody?
It may or may not work. We are accessing 6th element of array , where as it is declared to be array of 5 element.
Dear rockstar...
Visual studio is giving wrong results...How did you checked my dear friend ?
Address of variable i - -4201868
Address of array element 0 - -4201896
Address of variable i - -4201868
Address of array element 1 - -4201892
Address of variable i - -4201868
Address of array element 2 - -4201888
Address of variable i - -4201868
Address of array element 3 - -4201884
Address of variable i - -4201868
Address of array element 4 - -4201880
Address of variable i - -4201868
Address of array element 5 - -4201876
As you can see compiler kept some spacing between array allocation and int allocation, if you run the loop 2 more times, it will overwrite address of i and then it becomes infinite loop.
why this printf not working...
- Anonymous March 17, 2011have answer?
it goes into infinite loop, look at the for loop condition. i<=5 ,
which actually(array[5]) outer to the array. And in storage in stack
this will overwrite the i=0 ,( array[5] is the same as i's mem location.)
and it goes to infinite loop ,
cheers..