Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is the output of this C code?

#include <stdio.h>
    int x = 0;
    void main()
    {
        int *ptr = &x;
        printf("%p\n", ptr);
        x++;
        printf("%p\n ", ptr);
    }

 

  • A.Same address
  • B.Different address
  • C.Compile time error
  • D.Varies

Answer: A

Correct answer: Same address

ptr holds the address of x, and incrementing x changes the value stored there, not where it is stored. An object does not move during its lifetime.

So both printf calls print the same pointer value. The distinction is the one beginners most often blur: x++ alters the contents of the box, ptr++ would alter which box is pointed at, and only the second changes what %p reports.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.