Const array pointer to const values

Casey Kuball picture Casey Kuball · Aug 7, 2012 · Viewed 13.2k times · Source

If I create a global array of const values, e.g.

const int SOME_LIST[SOME_LIST_SIZE] = {2, 3, 5, 7, 11};

is it possible for SOME_LIST to be modified in any way?

How can I write this such that SOME_LIST points to a const memory location, and is a const pointer itself (i.e. cannot be pointed somewhere else)?

Answer

FreelanceConsultant picture FreelanceConsultant · Aug 7, 2012

There are 3 main examples of pointers which involve the "const" keyword. (See this link)

Firstly: Declaring a pointer to a constant variable. The pointer can move, and change what is it pointing to, but the variable cannot be modified.

const int* p_int;

Secondly: Declaring an "unmovable" pointer to a variable. The pointer is 'fixed' but the data can be modified. This pointer must be declared and assigned, else it may point to NULL, and get fixed there.

int my_int = 100;
int* const constant_p_int = &my_int;

Thirdly: Declaring an immovable pointer to constant data.

const int my_constant_int = 100; (OR "int const my_constant_int = 100;")
const int* const constant_p_int = &my_constant_int;

You could also use this.

int const * const constant_p_int = &my_constant_int;

Another good reference see here. I hope this will help, although while writing this I realize your question has already been answered...