Liste des Groupes | Revenir à cl c |
Suppose you have :
>
int v = 123; // Non-const object definition
const int * cp = &v; // Const pointer to non-const data
int * p = (int *) cp; // Cast to non-const pointer
*p = 456; // Change the target data
>
This is allowed, because the original object definition was not a const
definition.
>
However, with this:
>
int v = 123; // Const object definition
const int * cp = &v; // Const pointer to const data
int * p = (int *) cp; // Cast to non-const pointer
*p = 456; // Undefined behaviour
You can make the pointer to non-const, but trying to change an object that
was /defined/ as const is undefined behaviour (even if it was not placed in
read-only memory).
>
When you use dynamic memory, however, you are not defining an object in the
same way. If you write :
>
const int * cp = malloc(sizeof(int));
you are defining the object "p" as a pointer to type "const int" - but you
are not defining a const int. You can cast "cp" to "int *" and use that
new pointer to change the value.
Les messages affichés proviennent d'usenet.