Hello, everyone, today we are going to learn a written test question that may appear during the interview process
There is such a piece of code to analyze the running results of the VS compiler
#include<stdio.h>
int main()
{
int i = 0;
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
for (i = 0; i <= 12; i++)
{
arr[i] = 0;
printf("hehe\n");
}
return 0;
}
Many partners think that executing this code will print "hehe" 13 times and then the program will crash (array out-of-bounds access), what is the actual running result?
We found that the program did not crash, but kept printing "hehe", why?
Let's debug a bit of code:
We watch each value change while debugging:
After we keep pressing the f11 key, we find that the value of arr[12] always changes with the value of i, and we guess that i and arr[12] occupy the same memory space.
Through debugging, we also found that the addresses of arr[12] and i are the same:
When we first define the arr array, and then define the i program, the running results are different:
#include<stdio.h>
int main()
{
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
int i = 0;
for (i = 0; i <= 12; i++)
{
arr[i] = 0;
printf("hehe\n");
}
return 0;
}
At this point the program crashes:
And a question like this once appeared in a company's written test questions:
As long as we answer according to the way in the picture above, the 10-point questions can be easily obtained