Tag: programming languages

const pointer vs. pointer to const

Posted by – June 27, 2008


/*
ex. usage of a constant pointer to a (variable integer)
ex. how to fuck a pointer to a constant variable

*/
#include

int main(void)
{
const int c=0;
// constant pointer to a (variable) integer: can change the value of the var but not the pointer
int* const ptr1 = malloc(sizeof(int));
*ptr1 = 10;
*ptr1 = 100;

int t;
/* pointer to a constant integer: can change the pointer but not the variable (whatever is pointed to by ptr2 must be treated as a const, that’s why cannot change var value here). But of course if there are other pointers that point to the same area and are *not* const, var value can be changed. So, basically, with a const int* ptr2; we cannot change the area pointed to by ptr2 through ptr2 itself. But if *ptr2 (the value) is pointed to by another pointer… we can change it (*ptr2, the value)
*/

const int* ptr2 = malloc (sizeof(int));
int modvar = 10;

ptr2 = &modvar;
modvar = 100;

printf(“%d\n”, *ptr2);
return 0;
}