Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const array pointer to const values

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)?

like image 578
Casey Kuball Avatar asked Aug 07 '12 17:08

Casey Kuball


People also ask

Can pointer change const value?

A const pointer to a const value can not have its address changed, nor can the value it is pointing to be changed through the pointer. It can only be dereferenced to get the value it is pointing at.

Are arrays const pointers?

The name of the array A is a constant pointer to the first element of the array. So A can be considered a const int*. Since A is a constant pointer, A = NULL would be an illegal statement. Arrays and pointers are synonymous in terms of how they use to access memory.

How do you declare a pointer to a constant?

We can create a pointer to a constant in C, which means that the pointer would point to a constant variable (created using const). We can also create a constant pointer to a constant in C, which means that neither the value of the pointer nor the value of the variable pointed to by the pointer would change.

What is the difference between constant pointer and pointer to constant?

In the pointers to constant, the data pointed by the pointer is constant and cannot be changed. Although, the pointer itself can change and points somewhere else (as the pointer itself is a variable).


2 Answers

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...

like image 200
FreelanceConsultant Avatar answered Sep 28 '22 03:09

FreelanceConsultant


The way you have it is correct.

Also, you don't need to provide SOME_LIST_SIZE; C++ will figure that out automatically from the initializer.

like image 39
KRyan Avatar answered Sep 28 '22 03:09

KRyan