C Tutorial/Pointer/const pointer — различия между версиями

Материал из C\C++ эксперт
Перейти к: навигация, поиск
м (1 версия: Импорт контента...)
 
(нет различий)

Текущая версия на 13:32, 25 мая 2010

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

  1. ptr is a constant pointer to an integer that can be modified through ptr.
  2. 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>

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