const usage with pointers in C
I am going over C and have a question regarding const
usage with pointers. I understand the following code:
const char *someArray
This is defining a pointer that points to types of char and the const
modifier means that the values stored in someArray
cannot be changed. However, what does the following mean?
char * const array
Is this an alternate way of specifying a parameter that is a char pointer to an array named "array" that is const
and cannot be modified?
Lastly, what does this combination mean:
const char * const s2
For reference, these are taken from the Deitel C programming book in Chapter 7 and all of these are used as parameters passed to functions.
Solution 1:
const char*
is, as you said, a pointer to a char, where you can't change the value of the char (at least not through the pointer (without casting the constness away)).
char* const
is a pointer to a char, where you can change the char, but you can't make the pointer point to a different char.
const char* const
is a constant pointer to a constant char, i.e. you can change neither where the pointer points nor the value of the pointee.
Solution 2:
From what is the difference between const int*, const int * const, int const *:
Read it backwards...
int* - pointer to int int const * - pointer to const int int * const - const pointer to int int const * const - const pointer to const int
Solution 3:
//pointer to a const
void f1()
{
int i = 100;
const int* pi = &i;
//*pi = 200; <- won't compile
pi++;
}
//const pointer
void f2()
{
int i = 100;
int* const pi = &i;
*pi = 200;
//pi++; <- won't compile
}
//const pointer to a const
void f3()
{
int i = 100;
const int* const pi = &i;
//*pi = 200; <- won't compile
//pi++; <- won't compile
}