Thread: double pointer

  1. #1
    Registered User
    Join Date
    Oct 2022

    double pointer

    I know pointer hold address of another variable so pointer can hold location of another variable

    int main ()
    	int a = 10;
    	int *ptr = &a;
    	printf("location of ptr %p \n", &ptr);
    	int *dptr = &ptr;
    	printf(" dptr hold address of ptr is : %p", dptr);
    	return 0;
    location of ptr 0061FF14
    dptr hold address of ptr is : 0061FF14

    Pointer can store address of pointer and double pointer can also share address of pointer

    what's advantage of double pointer ?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Your code doesn't compile.
    $ gcc foo.c
    foo.c: In function ‘main’:
    foo.c:8:21: warning: initialization of ‘int *’ from incompatible pointer type ‘int **’ [-Wincompatible-pointer-types]
        8 |         int *dptr = &ptr;
          |                     ^
    > what's advantage of double pointer ?
    Allocating a 2D array.
    Typically like this.
    int **twod = malloc( 10 * sizeof(*twod));
    for ( int i = 0 ; i < 10 ; i++ ) 
        twod[i] = malloc( 100 * sizeof(*twod[i]) );
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Feb 2019
    Two other examples to add to Salem's answer... Let's say I want to make a function which closes a file, using a stream, and want to nullify this "ponter" after closing:
    void closefile( FILE **fptr )
      if ( *fptr ) fclose( *fptr );
      *fptr = NULL;
    The other is where you want an array of strings. A string, in C, is an array of chars where a pointer points to the first char, Like this:
    char *str = "fred";
    Here "fred" (and the final NUL char) is allocated somewhere in memory and the address to the first element is assigned to str. But what if you want an array of strings?
    char *strs[] = { "fred", "was", "here", NULL };
    strs points to the first pointer, which points to "fred"... We can use a pointer to a pointer of char to iterate through this array:
    char **p = strs;
    while ( *p )
      puts( *p++ );
    Last edited by flp1969; 01-11-2023 at 04:05 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 03-01-2015, 12:39 AM
  2. Double liked list and double pointer
    By saillesh.sabari in forum C Programming
    Replies: 1
    Last Post: 12-10-2010, 11:03 AM
  3. Replies: 4
    Last Post: 10-31-2009, 07:18 PM
  4. Replies: 3
    Last Post: 10-30-2009, 04:41 PM
  5. Replies: 5
    Last Post: 04-04-2009, 03:45 AM

Tags for this Thread