const int i = 10;
int *ptr;
*ptr = &i; // this line is wrong
You've made a mistake here that doesn't have anything to do with const
. When you declare a pointer you write TYPE *ptr
, but the star is not part of the name of the pointer. When you write *ptr = EXPRESSION;
, that means to store the value of EXPRESSION in the location that ptr
points to. But you didn't set ptr
to point to anything in particular yet, so the program will malfunction.
To set the location, which is what you're trying to do, you must instead write ptr = EXPRESSION
with no star:
int *ptr;
ptr = &i; // corrected
In the second test program, you had instead
int *ptr = &i;
which declares the pointer and sets its location in one step. It is shorthand for the "corrected" code above.
This is Just One Of Those Things You Have To Memorize when you are learning C.
Independent of all that, when you have
const int i = 10;
you can write code that looks like it modifies the value of i
using a non-const pointer, but that code -- however it is structured, however the pointer comes to point to i
-- is incorrect. A "better" programming language would refuse to compile that code. C implementations, almost entirely for historical reasons, will usually compile that code with maybe a warning if you're lucky, but the program you get is said to have "undefined behavior" -- it might do exactly what it looks like it does, it might behave as-if you had never modified the constant variable at all, it might crash, it might make demons fly out of your nose, none of these are considered to be wrong.
("Dereferencing" a pointer that hasn't been set to point to anything in particular also produces a program with undefined behavior.)