apointer.c
==========

/* Sort words lexicographically using an array of pointers */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXWORD	50
#define	N	1000 /* size of the pointer array */

main()
{
  char *w[N];		/* an array of pointers to words */
  char word[MAXWORD];	/* current word */
  int n;		/* no. of words to be sorted */
  int i;
  void sort_words(char *[], int);

  for (i = 0; scanf("%s", word) == 1; ++i) {
    if ( i >= N) {
	printf("Sorry, at most %d words can be sorted.", N);
	exit(1);
    }
    w[i] = calloc(strlen(word) + 1, sizeof(char));
    strcpy(w[i], word);
  }
  n = i;
  sort_words(w, n);
  for (i = 0; i < n; ++i) /* print the sorted words */
    printf("%s\n", w[i]);
}







void sort_words(char *w[], int n) /* n elements are to be sorted */
{
  int i, j;
  void swap(char **, char **);

  for (i = 0; i < n; ++i)
    for (j = i + 1; j < n; ++j)
      if (strcmp(w[i], w[j]) > 0)
	swap(&w[i], &w[j]);
}

void swap(char **p, char **q)
{
  char *temp;

  temp = *p;
  *p = *q;
  *q = temp;
}


apointer.dat
============

enjoy life after sunrise


gcc -ansi apointer.c -o apointer

apointer < apointer.dat

after
enjoy
life
sunrise