Pointers and qualifiers in C: What happens when calling fun(&ptr) if fun expects int ** but ptr has type const int * in the given program?

Difficulty: Easy

Correct Answer: Error: cannot convert parameter 1 from 'const int **' to 'int **'

Explanation:


Introduction / Context:
Type qualifiers such as const are part of a variable’s type in C. When you add layers of indirection (pointers to pointers), discarding qualifiers through an implicit conversion becomes dangerous and therefore illegal. This question explores why passing the address of a const int * to a function parameter of type int ** is ill-formed, even though both involve pointers to pointers conceptually.


Given Data / Assumptions:

  • ptr is declared as const int *ptr = &i;
  • fun is declared as int fun(int **ptr) and is called as fun(&ptr);
  • The function body later tries to redirect the pointer to a non-const int (via a temporary).


Concept / Approach:

  • A parameter of type int ** allows the callee to store an int * into the caller’s pointer.
  • But the caller’s pointer is a const int *, meaning it may not point to a modifiable int. Allowing an int ** parameter would permit the callee to assign a non-const int * into that location, breaking const-correctness.
  • Therefore, conversion from const int ** to int ** is prohibited to preserve type safety.


Step-by-Step Solution:

Caller provides &ptr → type is const int **.Callee expects int ** → types are not compatible.Compiler emits a diagnostic: cannot convert from const int ** to int **.Program fails to compile; no runtime output is produced.


Verification / Alternative check:

Consider what would happen if allowed: callee writes an int * pointing to modifiable memory into the location of a const int *; the caller could then modify an object that was intended to be read-only. The restriction prevents this.


Why Other Options Are Wrong:

  • Printing addresses or values implies successful compilation; it does not.
  • Garbage value: irrelevant because compilation already fails.
  • ”Address of i Address of j”: presumes behavior that cannot occur under strict type checking.


Common Pitfalls:

  • Confusing top-level const (the pointer itself) with low-level const (the pointed-to object). The latter is what blocks the conversion here.
  • Using casts to silence the error; this risks undefined behavior by violating const-correctness.


Final Answer:

Error: cannot convert parameter 1 from 'const int **' to 'int **'

More Questions from Constants

Discussion & Comments

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