But doesnt int const *p mean, constant pointer to an int ??
It's pointer-to-const-integer, quite different from constant pointer to integer. It will crash not because of 'const' but because you assigning p to an invalid memory. You can only do this with a variable. The purpose of this is just to prevent you from using the pointer to change the value of whatever the pointer points to. Remember that pointer stores address, so since the pointer itself is not const, you can change the value that pointer store, which is the address of another variable.
Code:
int var_1 = 5;
int var_2 = 6;
int const * p = &var; // works
p = &var_2; // works;
*p = 7; // fails, can't use pointer to change value pointed to.
int const *p = malloc( sizeof (int) ) ;
*p = 5; // this will fail.
One thing though, var_1 and var_2 don't have to be const. You use "const" just to prevent the pointer 'p' from changing the values of that object it points to.
Moreover,
Code:
int const * p;
const int * p;
These are equivalent. it just says that 'p' points to a constant object. you can't use *p to change the value that 'p' point too. However ++p works since 'p' itself is not const.
Code:
int * const p = malloc( sizeof( int ) ) ;
p++; // this will fail because p is const pointer
p = &var_1; // fails;
p = &var_2; // fails;
*p = 7; // works
if you use the declaration above, then 'p' is a const pointer. in this case 'p++' or '++p' will fail because the location that 'p' is const. but "*p = 10" is ok.
Code:
int const * const p = &var_1;
p++; // fails;
p = &var_2; // fails;
*p = 10; // fails;
You can make 'p' a constant pointer to const object by using the code above. One thing though, var_1 and var_2 don't have to be const. You use "const" just to prevent the pointer 'p' from changing the values of that object it points to.