Intel Interview Question
Software Engineer / Developersthis is a simple question, if anybody asks you this he's just trying to sniff your experience in programming or just thinks you're full of it and doesn't want to waste his time with good questions.
double pointers are used to either access encapsulated data, like a 2d array, or to give a function the option to change current pointer
for exp, a LL.
void add(node **head);
in this case you can do it without the double pointer but then it's less fun.
however in BSTs you can't boast doing addNode or delNode without a double pointer.
Double pointers are used in situations where the pointer itself is manipulated (apart from contents), and the changed pointer must be reflected back to the caller.
More clearly, when do we use pointers ??
When the value pointed by a pointer is changed, and the changes are reflected back to the caller.
Similarly, when the pointer itself is changed, and the changes are reflected back to the caller, we use double pointer.
Changing the pointer itself makes sense, for instance, when you have a string, or an array. When you want to run down a string, and retain the pointer position in the caller.
Double pointers is used for:
bi-directional, non-random access.
O(1) deletion/insertion.
O(n) access.
One of the most common application of a double pointer, I have came across, is for dynamically allocating a 2d array.
- Jeee November 12, 2006for e.g. if we want a 2d array (arr[2][3]) and access it by indexing, we can use the foll. code snippet.
int **arr;
arr = (int **) malloc (2 * sizeof(int *));
for( i = 0; i < 2; i++ )
{
arr[i] = (int *) malloc (3 * sizeof(int));
}
//The code will allocate memory for arr dynamically and we can access elemts of arr by indexing...