سؤال

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

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top