How to use the constant pointer
Description
Constant pointer points non-changing address.
Syntax
int count = 43;
int *const pcount = &count; /* Defines a constant */
Example
In the following code
ptr
is a constant pointer to an integer that can be modified through ptr
.
ptr
always points to the same memory location.
#include <stdio.h>
// ww w. ja v a 2 s . c o m
int main()
{
int x;
int y;
int* const ptr = &x;
*ptr = 7; /* allowed: *ptr is not const */
// ptr = &y; /* error: ptr is const; cannot assign new address */
return 0;
}
Example 2
We can also make a constant pointer for function parameter.
#include <stdio.h>
/*from www . j a v a 2s . c o m*/
void f( const int *xPtr );
int main()
{
int y;
f( &y );
return 0;
}
void f( const int *xPtr )
{
//*xPtr = 100; /* error: cannot modify a const object */
}