Friday, January 1, 2010

8.8 ARRAYS OF POINTERS

A multidimensional array can be expressed in terms of an array of pointers rather than a pointer to a group of contiguous arrays, .in such situations the newly defined array will have one less dimension than the original multidimensional array. Each pointer will indicate the begining of a seperate (n-1) dimensional array.

In general terms, a two-dimensional array can be defined as a one-dimensional array of pointers by writing

data-type *array[expression 1];

rather than a conventional array definition,


data-type array[expression 1][expression 2];

Similarly, an n-dimensional array can be defined as an (n-1) dimensional array of pointers by writing

data-type *array[expression 1][expression 2]......[expression n-1];

rather than

data-type array[expression 1][expression 2]......[expression n];

In these declarations data-type refers to the data type of the original one-dimensional,array is the array name,expression 1,expression 2,......,expression n are positive-valued integer expressions that indicate the maximum number of elements associated with each subscript.

You can notice that array name and its preceding asterisk are not enclosed in parentheses in this type of declaration.

Let us now approach the problem of entering a list of strings into the computer and rearranging them into alphabetical order using a one-dimensional array of pointers, where each pointer indicates the
begining of a string.

/*sort a list of strings into alphabetical otder using an array of pointers*/

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

void reorder(int n, char *x[]);

main()
{
int i, n=0;
char *x[10];

printf("Enter each string on a seperate line below\n\n");
printf("Type \'END\' when finished\n\n");

/*read in the list of strings*/
do {
/*allocate memory*/
x[n] = (char *)malloc(12 *sizeof(char));

printf("string %d", n+1);
scanf("%s", x[n]);
}

while(strcmp(x[n++], "END"));


/*reorder the list of strings*/
reorder(--n, x);


/*display the reordered list of strings*/
printf("\n\nReordered list of strings:\n");
for (i=0; i < n;++i)
printf("\nstring  %d: %s", i+1, x[i]);
}



void reorder(int n, char *x[])    /*rearrange the list of strings*/
{

char *temp;
int i, item;


for (item=0; item < n-1; ++item)


/*find the lowest of all remaining strings*/
for (i= item+1; i < n; ++i)
if (strcmp(x[item], x[i] ) > 0)   {
/*interchange the two strings*/
temp = x[item];
x[item] = x[i];
x[i] = temp;

}

return;

}

No comments:

Post a Comment