C Programming

SAMPLE CODE FOR POINTERS TO FUNCTIONS
Pointers to functions allow the creation of jump tables and dynamic routine selection. A pointer is assigned the start address of a function, thus, by typing the pointer name, program execution jumps to the routine pointed to.

By using a single pointer, many different routines could be executed, simply by re-directing the pointer to point to another function. Thus, programs could use this to send information to a printer, console device, tape unit etc, simply by pointing the pointer associated with output to the appropriate output function!

The following program illustrates the use of pointers to functions, in creating a simple shell program which can be used to specify the screen mode on a CGA system.


#include <stdio.h>      /* Funcptr.c */
#include <dos.h>

#define dim(x) (sizeof(x) / sizeof(x[0]) )
#define GETMODE        15
#define SETMODE         0
#define VIDCALL         0X10
#define SCREEN40        1
#define SCREEN80        3
#define SCREEN320       4
#define SCREEN640       6
#define VID_BIOS_CALL(x)  int86( VIDCALL, &x, &x )

int cls(), scr40(), scr80(), scr320(), scr640(), help(), shellquit();
union REGS regs;

struct command_table
{
  char *cmd_name;
  int (*cmd_ptr) ();
} cmds[]={"40",scr40,"80",scr80,"320",scr320,"640",scr640,"HELP",help,"CLS",cls,"EXIT",\
               shellquit};

cls()
{
  regs.h.ah = GETMODE;     VID_BIOS_CALL( regs );
  regs.h.ah = SETMODE;     VID_BIOS_CALL( regs );
}

scr40()
{
  regs.h.ah = SETMODE;
  regs.h.al = SCREEN40;
  VID_BIOS_CALL( regs );
}

scr80()
{
  regs.h.ah = SETMODE;
  regs.h.al = SCREEN80;
  VID_BIOS_CALL( regs );
}

scr320()
{
  regs.h.ah = SETMODE;
  regs.h.al = SCREEN320;
  VID_BIOS_CALL( regs );
}

scr640()
{
  regs.h.ah = SETMODE;
  regs.h.al = SCREEN640;
  VID_BIOS_CALL( regs );
}

shellquit()
{
   exit( 0 );
}

help()
{
   cls();
   printf("The available commands are; \n");
   printf("    40    Sets 40 column mode\n");
   printf("    80    Sets 80 column mode\n");
   printf("   320    Sets medium res graphics mode\n");
   printf("   640    Sets high res graphics mode\n");
   printf("   CLS    Clears the display screen\n");
   printf("  HELP    These messages\n");
   printf("  EXIT    Return to DOS\n");
}

get_command( buffer )
char *buffer;
{
  printf("\nShell: ");
  gets( buffer );
  strupr( buffer );
}

execute_command( cmd_string )
char *cmd_string;
{
  int i, j;
  for( i = 0; i < dim( cmds); i++ )
  {
    j = strcmp( cmds[i].cmd_name, cmd_string );
    if( j == 0 )
    {
      (*cmds[i].cmd_ptr) ();
      return 1;
    }
  }
  return 0;
}

main()
{
  char input_buffer[81];
  while( 1 )
  {
    get_command( input_buffer );
    if( execute_command( input_buffer ) == 0 )
      help();
  }
}


©Copyright B Brown. 1984-1999. All rights reserved.