Converting Pointers: Why Restrictions on Pointer-to-Pointer Conversions?
In C , it's generally permissible to cast a pointer to a non-const type to a pointer to a const type. This follows the principle of "const-correctness," allowing only constant data to be modified.
However, a peculiar exception arises when dealing with pointers to pointers. Unlike the aforementioned conversion, it's prohibited to convert a "pointer to pointer to non-const" to a "pointer to pointer to const."
Consider this code snippet:
char *s1 = 0; const char *s2 = s1; // OK... char *a[MAX]; // aka char ** const char **ps = a; // error!
Why is the assignment of a to ps illegal? The answer lies in the standard:
const char c = 'c'; char* pc; const char** pcc = &pc; // not allowed *pcc = &c; *pc = 'C'; // would allow to modify a const object
In this example:
If this conversion were allowed, it would enable modifications to constant objects. For instance, *pcc would point to a const character, but *pc would be modifiable. This violates the premise of const-correctness, as it potentially permits changes to constant data.
Therefore, the restriction on converting a pointer to pointer to non-const to a pointer to pointer to const stems from the need to maintain the integrity of constant objects and prevent unintended data modifications.
The above is the detailed content of Why Can't I Convert a Pointer-to-Pointer to Non-Const to a Pointer-to-Pointer to Const in C ?. For more information, please follow other related articles on the PHP Chinese website!