Sunday, August 17, 2014

Pointer array and its advantage

Pointer array:


In general, an array of pointers can be used to point to an array of data items with each element of the pointer array pointing to an element of the data array. Data items can be accessed either directly in the data array, or indirectly by dereferencing the elements of the pointer array.

Adv:
he advantage of a pointer array is that the pointers can be reordered in any manner without moving the data items. For example, the pointer array can be reordered so that the successive elements of the pointer array point to data items in sorted order without moving the data items. Reordering pointers is relatively fast compared to reordering large data items such as data records or strings. This approach saves a lot of time, with the additional advantage that the data items remain available in the original order. Let us see how we might implement such a scheme.



reference:
http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.4.html#fig114


program 2 for the same:


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

void SortNames(char** ppchNames, int iCount)
{
  int i,j;
  for (j = 0; j < iCount -1; j++) {
    for (i = 0; i < iCount -1-j; i++) {
      if (0 < strcmp(ppchNames[i], ppchNames[i +1])) {
        char* pchTemp = ppchNames[i];
        ppchNames[i] = ppchNames[i +1];
        ppchNames[i +1] = pchTemp;
      }
    }
  }
}

void PrintNames(char** ppchNames, int iCount)
{
  int i;
  for (i = 0; i < iCount; i++) {
    printf("%s\n", ppchNames[i]);
  }
}
int main()
{
  char* name[] = {
                  "January",
                  "February",
                  "March",
                  "April",
                  "May",
                  "June",
                  "July",
                  "August",
                  "September",
                  "October",
                  "November",
                  "December"
                 };

  printf("-- before:\n");

  PrintNames(name, 12);

  SortNames(name, 12);

  printf("-- after:\n");

  PrintNames(name, 12);
  return 0;
}

No comments:

Post a Comment