#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();
}
---------------------------------------------------------------------------
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