The following program demonstrates a significant processing operation on arrays of strings. More precisely, we present the re-sorting of a set of strings in order to classify them. So, we read the strings and place them in a temporary storage area (buffer) large enough to be able to store all, keeping in an array a pointer to each string. Then we re-sort the pointers (only pointers and not strings to increase the performance) to place the pointer to the “smallest” string at the first position of the array, the pointer to the next “largest” string at the second position of the array, and so on.

You should know that the implementation of the algorithm does not take into account issues of data input validation or proper management of dynamic memory (e.g. avoiding memory leaks) because it is only necessary to highlight the logic of the algorithm.

#include <iostream>
#include <cstdlib>
#include <cstring>

using namespace std;

const int N_MAX = 1000;
const int M_MAX = 10000;

int
compare (const void * i, const void * j) {
  return strcmp (*(char **) i, *(char **) j);
}

int
main () {
  int N, M = 0;

  char * sorted[N_MAX], buffer[M_MAX];

  for (N = 0; N < N_MAX; N++) {
    sorted[N] = &buffer[M];

    if (!(cin >> sorted[N]))
      break;

    M += strlen (sorted[N]) + 1;
  }

  qsort (sorted, N, sizeof (char *), compare);

  for (int i = 0; i < N; i++)
    cout << sorted[i] << endl;

  return EXIT_SUCCESS;
}