Const pointer vs pointer to const: identify the actual error in reassignment #include<stdio.h> int main() { char mybuf[] = "India"; char yourbuf[] = "CURIOUSTAB"; char const ptr = mybuf; / const pointer to char (pointer is fixed) */ ptr = 'a'; / writing through ptr is allowed (mybuf is writable) / ptr = yourbuf; / ERROR: cannot reassign a const pointer */ return 0; }

Difficulty: Easy

Correct Answer: None of above

Explanation:

Introduction / Context:This question distinguishes between “const pointer to T” (T *const) and “pointer to const T” (const T *). Here, the pointer itself is const, so it cannot be reseated to point elsewhere, although the data it points to is modifiable.

Given Data / Assumptions:

  • ptr is declared char *const ptr = mybuf;
  • mybuf and yourbuf are writable arrays.
  • *ptr = 'a' modifies the first character of mybuf—this is legal.
  • ptr = yourbuf; attempts to reassign the const pointer—this is illegal.

Concept / Approach:A const pointer cannot have its stored address changed after initialization. The error is not a “conversion” but an assignment to a const object. Typical diagnostics: “assignment of read-only variable ‘ptr’.” None of the listed answers (a–c) precisely describe this, so “None of above” is correct.

Step-by-Step Solution:Declare const pointer: ptr fixed to mybuf.Write through ptr: allowed because the pointee type is non-const.Attempt to reassign ptr: forbidden → compile-time error.

Verification / Alternative check:Change declaration to char *ptr = mybuf; and reassignment compiles. Or change to const char *ptr = mybuf; and note you cannot write *ptr = 'a', showing the orthogonal roles of the two "const" positions.

Why Other Options Are Wrong:(a) and (b) mischaracterize the issue as conversion. (c) claims no error, but reassignment of a const pointer is invalid. (e) suggests a runtime failure; the failure is at compile time.

Common Pitfalls:Mixing up T *const with const T *; thinking const always applies to the pointee rather than the pointer itself.

Final Answer:None of above

More Questions from Constants

Discussion & Comments

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