C Pointers – Usage of Double Pointers and N Pointers

cpointers

I am familiar with basic C pointers. Just wanted to ask what is the actual use of double pointers or for that matter n pointer?

#include<stdio.h>
int main()
{
    int n = 10 , *ptr , **ptr_ptr ;
    ptr = &n;
    ptr_ptr = &ptr;
    printf("%d", **ptr_ptr);
    return(0);
}

**ptr_ptr is printing 10 but how?

Best Answer

ptr_ptr is a pointer to a pointer to an int, and it points at ptr. ptr is a pointer to an int, and it points at n. n is an int, which has been set to 10.

A prefix '*' is the de-reference operator, meaning "the thing pointed to by". So **ptr_ptr evaluates to *ptr which evaluates to n, which is 10. If it helps, consider **ptr_ptr as equivalent to *(*ptr_ptr).

What's it for? Two possible uses are

  1. Passing a pointer as a parameter to a function, where you want the function to be able to change the pointer to a different one.
  2. Passing an array of pointers to a function, as in the classic int main(int argc, char **argv).

I have never encountered any need for an int ***ptr_ptr_ptr, but it's valid C.