//--------------------------------------------------------------------
// funcptr.cpp
//--------------------------------------------------------------------

// Examples showing the use of pointers as function parameters and // of functions that return a pointer.
#include <iostream.h>
// Function prototypes void printSum ( int *numPtr1, int *numPtr2 ); void swap ( int *numPtr1, int *numPtr2 ); void copyString ( char *dest, char *source ); char *match ( char *str, char searchCh );
//--------------------------------------------------------------------
void main() { int val1 = 10, // Sample integer values val2 = 20; char alpha[11] = "alpha", // Sample strings beta[11]; char sample[11] = "Sample", *ptr;
// Prints the sum of two integer values. cout << endl << "The sum of val1 and val2 is "; printSum(&val1,&val2);
// Swaps two integer values. swap(&val1,&val2); cout << "After swapping" << endl; cout << "val1: " << val1 << endl << "val2: " << val2 << endl;
// Copy alpha to beta. copyString(beta,alpha); cout << "After copying" << endl; cout << "alpha: " << alpha << endl << "beta: " << beta << endl;
// Find a match for character 'p' in sample. ptr = match(sample,'p'); cout << "Match character: " << *ptr << endl; }
//--------------------------------------------------------------------
void printSum ( int *numPtr1, int *numPtr2 ) // Outputs the sum of the integer values pointed to by numPtr1 and // numPtr2. { cout << *numPtr1 + *numPtr2 << endl; }
void swap (int *numPtr1, int *numPtr2) // Exchanges the integer values pointed to by numPtr1 and numPtr2. { int temp;
temp = *numPtr1; *numPtr1 = *numPtr2; *numPtr2 = temp; }
void copyString ( char *dest, char *source ) // Copies source string to dest string buffer. Note that strings // source and dest are passed using pass-by-reference. { while ( *source != '\0' ) // Stop when null reached in source { *dest = *source; // Copy character source++; // Advance to next character in source dest++; // Advance to next character in dest } *dest = '\0'; // Add null character to dest }
/*
void copyString ( char *dest, char *source ) // Copies source string to dest string buffer. Uses the subscript // operator to access the characters in the strings. { int index = 0; while ( source[index] != '\0' ) // Stop when null is reached { dest[index] = source[index]; // Copy character index++; // Advance to the next character } dest[index] = '\0'; // Add null character to dest }
*/
char *match ( char *str, char searchCh ) // Returns a pointer to the first character in string str that // matches character searchCh. If there are no matches, then // returns the null pointer. { char *matchPtr = str; // Pointer returned
// Search for searchCh by advancing matchPtr through the string. while ( *matchPtr != searchCh && *matchPtr != '\0' ) matchPtr++;
if ( *matchPtr == '\0' ) matchPtr = 0; // searchCh not found, return null
return matchPtr; }