C Tutorial/Pointer/const pointer
Содержание
A non-constant pointer to constant data
<source lang="cpp">#include <stdio.h> void printCharacters( const char *sPtr ); int main() {
char string[] = "print characters of a string"; printf( "The string is:\n" ); printCharacters( string ); printf( "\n" ); return 0;
} void printCharacters( const char *sPtr ) {
for ( ; *sPtr != "\0"; sPtr++ ) { printf( "%c", *sPtr ); }
}</source>
The string is: print characters of a string
Attempting to modify a constant pointer to non-constant data
- ptr is a constant pointer to an integer that can be modified through ptr.
- ptr always points to the same memory location.
<source lang="cpp">#include <stdio.h>
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;
}</source>
Attempting to modify data through a non-constant pointer to constant data.
xPtr cannot be used to modify the value of the variable to which it points.
<source lang="cpp">#include <stdio.h>
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 */
}</source>
Using a non-constant pointer to non-constant data
<source lang="cpp">#include <stdio.h>
- include <ctype.h>
void convertToUppercase( char *sPtr ); /* prototype */ int main() {
char string[] = "characters and abcde"; printf( "The string before conversion is: %s", string ); convertToUppercase( string ); printf( "\nThe string after conversion is: %s\n", string ); return 0;
} void convertToUppercase( char *sPtr ) {
while ( *sPtr != "\0" ) { if ( islower( *sPtr ) ) { *sPtr = toupper( *sPtr ); } ++sPtr; }
}</source>
The string before conversion is: characters and abcde The string after conversion is: CHARACTERS AND ABCDE