Const Pointers
suggest changeSingle Pointers
- Pointer to an
int
The pointer can point to different integers, and the int can be changed through the pointer. This sample points p at b, then stores 100 through p.
int b;
int* p;
p = &b; /* OK */
*p = 100; /* OK */
- Pointer to a
const int
The pointer can point to different integers, but the int's value cannot be changed through the pointer.
int b;
const int *p;
p = &b; /* OK */
*p = 100; /* Compiler error */
constpointer toint
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 */
constpointer toconst int
The pointer can point to only one int, and that int cannot 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
- Pointer to a pointer to an
int
This code stores the address of p1 in the pointer to pointer p. It then points p1 at a and stores 100 in a.
void f1(void)
{
int a, b;
int *p1;
int **p;
p1 = &b; /* OK */
p = &p1; /* OK */
*p = &a; /* OK */
**p = 100; /* OK */
}
- Pointer to pointer to a
const int
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’ */
}
- Pointer to
constpointer to anint
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 */
}
constpointer to pointer toint
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 */
}
- Pointer to
constpointer toconst int
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’ */
}
constpointer to pointer toconst int
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’ */
}
constpointer toconstpointer toint
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 */
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents