Const Pointers

suggest change

Single Pointers

The pointer can point to different integers and the int’s can be changed through the pointer. This sample of code assigns b to point to int b then changes b’s value to 100.

int b;
int* p;
p = &b;    /* OK */
*p = 100;  /* OK */
The pointer can point to different integers but the `int`'s value can't be changed through the pointer.

  int b;
  const int* p;
  p = &b;    /* OK */
  *p = 100;  /* Compiler Error */

The pointer can only point to one int but the int’s value can be changed through the pointer.

int a, b;
int* const p = &b; /* OK as initialisation, no assignment */
*p = 100;  /* OK */
p = &a;    /* Compiler Error */

The pointer can only point to one int and the int can not be changed through the pointer.

int a, b;
const int* const p = &b; /* OK as initialisation, no assignment */
p = &a;   /* Compiler Error */
*p = 100; /* Compiler Error */

Pointer to Pointer

This code assigns the address of p1 to the to double pointer p (which then points to int* p1 (which points to int)).

Then changes p1 to point to int a. Then changes the value of a to be 100.

void f1(void)
  {
    int a, b;
    int *p1;
    int **p;
    p1 = &b; /* OK */
    p = &p1; /* OK */
    *p = &a; /* OK */
    **p = 100; /* OK */
  }
void f2(void)
{
 int b;
 const int *p1;
 const int **p;
 p = &p1; /* OK */
 *p = &b; /* OK */
 **p = 100; /* error: assignment of read-only location ‘**p’ */
}
void f3(void)
{
  int b;
  int *p1;
  int * const *p;
  p = &p1; /* OK */
  *p = &b; /* error: assignment of read-only location ‘*p’ */
  **p = 100; /* OK */
}
void f4(void)
{
  int b;
  int *p1;
  int ** const p = &p1; /* OK as initialisation, not assignment */
  p = &p1; /* error: assignment of read-only variable ‘p’ */
  *p = &b; /* OK */
  **p = 100; /* OK */
}
void f5(void)
{
  int b;
  const int *p1;
  const int * const *p;
  p = &p1; /* OK */
  *p = &b; /* error: assignment of read-only location ‘*p’ */
  **p = 100; /* error: assignment of read-only location ‘**p’ */
}
void f6(void)
{
  int b;
  const int *p1;
  const int ** const p = &p1; /* OK as initialisation, not assignment */
  p = &p1; /* error: assignment of read-only variable ‘p’ */
  *p = &b; /* OK */
  **p = 100; /* error: assignment of read-only location ‘**p’ */
}
void f7(void)
{
  int b;
  int *p1;
  int * const * const p = &p1; /* OK as initialisation, not assignment */
  p = &p1; /* error: assignment of read-only variable ‘p’  */
  *p = &b; /* error: assignment of read-only location ‘*p’ */
  **p = 100; /* OK */
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents