Home > Backend Development > C++ > Why Can't I Convert a Pointer-to-Pointer to Non-Const to a Pointer-to-Pointer to Const in C ?

Why Can't I Convert a Pointer-to-Pointer to Non-Const to a Pointer-to-Pointer to Const in C ?

Susan Sarandon
Release: 2025-01-01 02:42:09
Original
524 people have browsed it

Why Can't I Convert a Pointer-to-Pointer to Non-Const to a Pointer-to-Pointer to Const in C  ?

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!
Copy after login

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
Copy after login

In this example:

  1. c is a constant character.
  2. pc is a non-const pointer to a character.
  3. Attempting to initialize pcc (a pointer to a pointer to const) with &pc is disallowed.

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template