Monday, May 1, 2017

Constant and Ponter

const int *p is a pointer to a constant integer.  We cannot change the variable that the pointer is pointing to but we can change the pointer to point to another variable.  However, even if the new variable it points to is not a constant, C runtime will not allow us to change it as it thinks the pointer is pointing to a constant as declared.

For example

const int *p;
const int i = 100
int j = 20

p = &i;  /* ok */
p = &j;  /* ok */
*p = 300;  /* error */

int *const p is a constant point pointing to an integer variable.  The pointer value cannot be change but we can change the variable it points to.

*p = 100;  /* ok */
p = &j;  /* error */

const int *const p is a constant pointer pointing to a constant variable. When the pointer is declard, it must be initialized.

const int *const p = &i

const int *const *p is a pointer to a constant pointer to a constant integer variable

No comments: