Liste des Groupes | Revenir à cl c |
David Brown <david.brown@hesbynett.no> writes:Correction:
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
Fortunately, Usenet is a self-correcting medium :-) Thanks for pointing out that mistake, and I hope the OP sees your correction before getting confused by my copy-pasta error.const int * cp = &v; // Const pointer to const dataI think missed out the crucial "const" on the first line of the second
int * p = (int *) cp; // Cast to non-const pointer
*p = 456; // Undefined behaviour
example! It's always the way.
That's a common preference. Personally, I prefer the former - I think it makes it clearer that we are allocating space for an int. Hopefully the OP will hang around this group and we'll get a chance to give advice and suggestions on many different aspects of C programming.You can make the pointer to non-const, but trying to change an object thatI prefer
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));
const int *cp = malloc(sizeof *cp);
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.