Thursday, 19 January 2012

Program Of Array of Pointer In C++


#include<iostream.h>
#include<conio.h>
main()
{
clrscr();
int i,a[10],*ptr;
for(i=0;i<10;i++)
{
cout<<"Enter NUmber=";
cin>>a[i];
}

for(i=0;i<10;i++)
{
ptr = &a[i];
cout<<"\n Value of a["<<i<<"]==>"<<a[i]<<" And Address of a["<<i<<"]==>"<<ptr;

}

getch();
}

---------------------------------------------------------------------------



As seen in the last example, sorting an array of strings requires swapping the strings which can require copying a lot of data. For efficiency, it is better to avoid actual swapping of data whenever a data item is large, such as a string or an entire data base record. In addition, arrays may be needed in more than one order; for example, we may need an exam scores array sorted by Id number and by weighted scores; or, we may need strings in both an unsorted form and a sorted form. In either of these cases, we must either keep two copies of the data, each sorted differently, or find a more efficient way to store the data structure. The solution is to use pointers to elements of the array and swap pointers. Consider some examples:
int data1, data2, *ptr1, *ptr2, *save;

     data1 = 100; data2 = 200;
     ptr1 = &data1; ptr2 = &data2;
We could swap the values of the data and store the swapped values in data1 and data2 or we could simply swap the values of the pointers:
save = ptr1;
     ptr1 = ptr2;
     ptr2 = save;
We have not changed the values in data1 and data2; but ptr1 now accesses data2 and ptr2 access data1. We have swapped the pointer values so they point to objects in a different order. We can apply the same idea to strings:
char name1[] = "John";
     char name2[] = "Dave";
     char *p1, *p2, *save;

     p1 = name1;
     p2 = name2;
Pointers p1 and p2 point to strings name1 and name2. We can now swap the pointer values so p1 and p2 point to name2 and name1, respectively.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. The 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.


No comments:

Post a Comment