Hi All,
Could you kindly help me regarding the usage of array of pointer (1dimension or 2), I mean where we can use it.
Regards,
IDB
Array of Pointers can be used to do fast sorting.
For eg. If you want to sort a unsorted array of integer. You generally can use all sorts of algorithms on the int array. But it would be less efficient as the runtime head for moving the values of int array will be more.
Now other alternative is to sort by using array of pointers. Say, now, you create array to int pointers (int*) and let each one of them point to the corresponding elements of the integer array. Now when you need to sort them, just re-locate the pointers in correct order, which would be faster.
Read: http://www.gidforums.com/t-10801.html
Another use is to hold a collection of heterogeneous objects. For instance, if you have the classic example of things derived from Shape (triangle, circle, etc). If you make an array of Shape objects, then they are just base objects (not triangle etc). But if you make it an array of pointers to Shape, then you can access the derived classes polymorphically.
you can use them to dynamically initialize memory (mean that at runtime u decide the number of elements of the array)
for both 2d And 1d
You can use them e.g. for a table of char-strings:
#include <iostream>
using namespace std;
int main(void)
{
/* Declare the '2D Array' */
char ** ptr = new char * [5];
ptr[0] = new char[20];
ptr[1] = new char[20];
ptr[2] = new char[20];
ptr[3] = new char[20];
ptr[4] = new char[20];
/* Put some data in the array */
ptr[0] = "Hello ";
ptr[1] = "wond";
ptr[2] = "er";
ptr[3] = "ful";
ptr[4] = " world !!!";
/* Print the array on the screen */
for(int i = 0; i < 5; i++)
cout << ptr[i];
cout << endl;
/* Cleanup */
delete[] ptr;
/* Wait for the user to press ENTER */
cin.get();
/* Tell the Operating System that everything went well */
return 0;
}
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.