Why Not Garbage Values
Guys this is a program which i ran on my compiler and i am getting 30 0 0 0 as the output.Can one explain me why the values are 0 .Because in 2'nd loop tmp would 开发者_Python百科point to something outside the array so wouldn't it be a garbage value. Why Garbage values are not getting printed instead 0's are coming in the output.
void main()
{
int array[4]={10,20,30,40};
int *tmp=array;
for (int i=0;i<4;i++)
{
tmp+=sizeof(int);
printf("%d",*tmp);
}
getch();
}
You do not add sizeof(int)
to an int
pointer to get to the next array element; you add 1. Adding sizeof(int)
will advance by sizeof(int)
elements (probably 4 elements), putting you past the end of the array. This is your problem.
Edit: OK apparently the program was part of an interview question meant to illustrate undefined behavior, and the correct answer to the interview question is that once undefined behavior has been invoked, anything could happen.
0 can be a garbage value too. it depends on what is in the memory due to compiler switches etc.
try compiling your code in release mode and your probably will get other funny numbers
In this case the sizeof(int) is 2 bytes that is why it prints 30 (initially the pointer is pointing to memory location having value 10 and then it points to 30, it prints this value subsequently).
Next again the pointer moves ahead by 2 places so it skips 40 and moves out of bounds. 0 as has been stated earlier is a random garbage value though it looks as if the values are proper.Try executing the code again after declaring some more variables along with the array and observe the output.
精彩评论