Why does this code print 4 as the output?
Please also provide some details to help me to understand this type of behaviour better.
int main(){
int *p=NULL;
printf("%d" ,p+1);
return 0;
}
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.
You are getting undefined behavior. It is only valid to add an integer to a pointer if the pointer points to an element of an array or one beyond the end of an array and result of moving the pointer by the number of positions denoted by the integer also points to an element of the same array, or one beyond the end. (A non-array object can be treated as the only element of a one element array for these purposes.)
A null pointer doesn’t point at an element of an array so you can’t add one to it. (In C++ it is explicitly allowed to add 0 to a null pointer value and get a null pointer value as the result. (See this blog entry by Andrew Koenig at Dr. Dobb’s.)
You get further undefined behavior by passing a pointer value to
printfwhere the corresponding format specifier is%dwhich expects andint.%pis the correct format specifier forvoid*, you need an explicit cast if you want to print the pointer as anintwith%d.If your program has undefined behavior then there are no guarantees about anything that might happen. You certainly can’t infer anything about the language from observing the results and it is arguable what the merit there is trying to infer properties of the implementation from such behaviour as, without further evidence in the form of observable results from programs which don’t have undefined behavior or guarantees from the compiler vendor, you won’t know what circumstances might cause the observed behavior to change.