Printing through a pointer-to-const: In Turbo C, given const int *ptr pointing to i, then reassigned to j, what is the likely output of printing the pointer values (as hex) and the pointed integers?

Difficulty: Easy

Correct Answer: i= FFE4 ptr=10 j=FFE2 ptr=20

Explanation:


Introduction / Context:
A pointer-to-const (const int *) allows reading the pointed value but not modifying it. Reassigning the pointer itself to point to a different object is legal because the pointer is not const-qualified here. The program prints the address held in the pointer (using a hex-like format) and then the value obtained by dereferencing it, first for i and then after reassigning to j. While exact addresses vary, the pattern of printing the current address and associated value is predictable.


Given Data / Assumptions:

  • Two ints exist: i = 10 and j = 20.
  • const int *ptr = &i; then later ptr = &j;
  • The code prints the pointer value with %5X (non-portable for pointers) and then the dereferenced integer with %d.


Concept / Approach:

  • Pointer-to-const restricts writes through the pointer, not reassignment of the pointer variable.
  • Printing a pointer with %X is technically undefined in standard C; however, many DOS/Turbo C environments treated pointers and integers similarly, and the exercise expects a schematic address-value pairing.
  • Thus, the intended correct output shows two address prints (for &i and &j) and two integer prints (10 then 20).


Step-by-Step Solution:

Initialize ptr to &i → dereference prints 10 after showing some address.Reassign ptr to &j → dereference prints 20 after showing the new address.Among the options, only one displays values 10 and 20 in that order, paired with plausible hex addresses.


Verification / Alternative check:

Running analogous code on Turbo C typically yields two distinct near-pointer values and the expected integers. Modern compilers require using %p to print pointers portably.


Why Other Options Are Wrong:

  • Options with 12/24 or 20/30 imply different numeric values than the program stores.
  • Garbage value: while %X for pointers is non-portable, the exercise assumes meaningful display.
  • Compilation error due to const: reading through const int * is fine; only writing would error.


Common Pitfalls:

  • Believing const applies to the pointer itself; it applies to the pointed-to object in this declaration.
  • Using %X or %d for pointers in portable C; %p is the correct specifier with a cast to void *.


Final Answer:

i= FFE4 ptr=10 j=FFE2 ptr=20

More Questions from Constants

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion