In C, why does the following result in x[1] being 2?
int a = 2, x;
...
printf("x[1] = ", &x[1])
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It doesn’t. It results in undefined behaviour where anything can happen. You cannot access elements beyond the end of an array in a defined manner.
What’s most likely happening is that
ais just “above”xon the stack, which results inx[1]having the same address asa, but it’s by no means guaranteed.This is, of course, assuming that your
printfis a typo. As it stands, it doesn’t even compile. I’m assuming it’s a typo since the question title just asks about the value ofx[1]rather than the output.To get it to work, you’d have to use something like:
which also prints
2on my system, but may do something totally different elsewhere.