Tuesday, August 7, 2007

C quiz question

I was looking at coming up with a few small C/programming questions for a number of interviews that I am taking these days. Here is one that is interesting:

What would be the output in the following piece of code?
main()
{
int a[5] = {1,2,3,4,5};
int *ptr = (int*)(&a+1);

printf("%d %d" , *(a+1), *(ptr-1) );
}

I needed to compile and confirm, but the output in this case would be "2 5".
How we get "2", is obvious. The interesting one is how we get the "5".
The reason being ptr is a pointer to the array of integer. Not a pointer to an integer.
So when you do &a+1, you are pointing to the next array of integer, and not a[1].
Hence, when you do *(ptr - 1), you end up dereferencing a[4].

It gets interesting when I next ask you for output of the following piece of code:

main()
{
char a[5] = {'a','b','c','d','e'};
int *ptr = (int*)(&a+1);

printf("%c %c\n" , *(a+1), *(ptr-1) );
}

No comments: