Thread: Double pointers

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    6

    Double pointers

    Hi,

    I have had a nagging doubt about the double pointers & I would appreciate some clarification. The following code is an e.g. of double pointers. It works on linked list & creates a copy of a linked list (q).

    Code:
    copy_linked_lists(struct node *q, struct node **s)
    {
        if(q!=NULL)
        {
            *s=malloc(sizeof(struct node));
            (*s)->data=q->data;
            (*s)->link=NULL;
            copy_linked_list(q->link, &((*s)->link));
        }
    }
    I would like to know why this code has a double pointer passed to it. Suppose I "twist" the code to make it single pointered what could potentially go wrong with it.

    Code:
    copy_linked_lists(struct node *q, struct node *s)
    {
        if(q!=NULL)
        {
            s=malloc(sizeof(struct node));
            s->data=q->data;
            s->link=NULL;
            copy_linked_list(q->link, s->link);
        }
    }
    My understanding is double pointers are used when you don't want the address you are working on being destroyed in stack (as in function exit). Am I right? If so why I would really appreciate if someone can explain to me why the double pointer is used in the above code.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    To make a variable outside a function, keep a value assigned in a function, you need a pointer to it. Therefore, if you want a pointer outside a function, to keep a value you assign it in a function, you need its address (a pointer to it). Otherwise, you can't keep the value (unless you're assigning it via return).


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Testing some code, lots of errors...
    By Sparrowhawk in forum C Programming
    Replies: 48
    Last Post: 12-15-2008, 04:09 AM
  2. Need some help...
    By darkconvoy in forum C Programming
    Replies: 32
    Last Post: 04-29-2008, 03:33 PM
  3. calculations with pointers
    By mackieinva in forum C Programming
    Replies: 2
    Last Post: 09-17-2007, 01:46 PM
  4. C++ to C Conversion
    By dicon in forum C Programming
    Replies: 7
    Last Post: 06-11-2007, 08:38 PM
  5. Unknown Math Issues.
    By Sir Andus in forum C++ Programming
    Replies: 1
    Last Post: 03-06-2006, 06:54 PM