C Tutorial/Pointer/const pointer

Материал из C\C++ эксперт
Версия от 10:32, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A non-constant pointer to constant data

#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 );
   }
}
The string is:
print characters of a string

Attempting to modify a constant pointer to non-constant data

  1. ptr is a constant pointer to an integer that can be modified through ptr.
  2. ptr always points to the same memory location.


#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;
}

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.


#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 */
}

Using a non-constant pointer to non-constant data

#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;
   } 
}
The string before conversion is: characters and abcde
The string after conversion is: CHARACTERS AND ABCDE