Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C and C++ compiler give different messages for the following code, why?

Tags:

c++

c

I was asked to give the output of the following code in an interview.

int a[] = {1,2,3,4,5};
int *p = &a + 1;
printf("%d, %d", *(a+1), *(p - 1));

I said I could not determine the result of the second one, so I failed the interview.

When I got back to home, and tried to compile the code, g++ will report an error, but gcc will only give a warning. The result printed is '2,5'.

Anyone knows why the C and C++ compiler behave differently on this?

like image 631
bugs king Avatar asked Dec 02 '25 05:12

bugs king


1 Answers

a is an array of integers, which converts to a pointer to the first element when needed. a+1 invokes that conversion, and gives a pointer to the second element.

&a is a pointer to the array itself, not to the first element of it, so &a + 1 points beyond the end of the array (to the point where the second array would be, if it were a 2-dimensional array).

The code then converts that pointer (of type int (*)[5]) to a pointer to an integer (type int*). C++ doesn't allow such a conversion without an explicit reinterpret_cast, while C is more lenient in the pointer conversions it allows.

Finally (assuming that p and p2 are supposed to be the same thing), p - 1 points to the last element of a.

like image 151
Mike Seymour Avatar answered Dec 03 '25 20:12

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!