Search Contact information
University of Cambridge Home Department of Engineering
University of Cambridge >  Engineering Department >  computing help
next up previous contents
Next: A data filter Up: Examples Previous: Linked Lists   Contents

Using pointers instead of arrays

#include "stdio.h"
char *words[]={"apple","belt","corpus","daffodil","epicycle","floppy",
	       "glands","handles","interfere","jumble","kick","lustiness",
	       "glands","handles","interfere","jumble","kick","lustiness",
	       "glands","handles","interfere","jumble","kick","lustiness",
	       "glands","handles","interfere","jumble","kick","lustiness",
	       "glands","handles","interfere","jumble","kick","lustiness",
	       "glands","handles","interfere","jumble","kick","lustiness",
	       "glands","handles","interfere","jumble","kick","lustiness",
	       "glands","handles","interfere","jumble","kick","lustiness",
	       "glands","handles","interfere","jumble","kick","lustiness",
		"mangleworsel","nefarious","oleangeous","parsimonious",NULL};


void slow(void)
{
int i,j,count=0;
for (i=0; words[i] != NULL ; i=i+1)
     for (j=0; j <= strlen(words[i]) ; j=j+1)
         if(words[i][j] == words[i][j+1])
            count= count+1;
 printf("count %d\n",count);
}

void fast(void)
{
register char **cpp; /* cpp is an array of pointers to chars */
register char *cp;
register int count=0;

for (cpp= words; *cpp ; cpp++)     /* loop through words. The final 
                                      NULL pointer terminates the loop */
     for (cp = *cpp ; *cp ; cp++)  /* loop through letters of a word.
                                      The final '\0' terminates the loop */
        if(*cp == *(cp+1))
          count++;
 printf("count %d\n",count);
}


/*count the number of double letters, first using arrays, then pointers */
void main(int argc, char *argv[]){
   slow();
   fast();
}



Tim Love 2010-04-27