Thread: Pointer to pointer question

  1. #1
    Registered User
    Join Date
    Nov 2012
    Location
    Heraklion, Greece, Greece
    Posts
    26

    Pointer to pointer question

    What is the difference between
    Code:
    #include<stdlib.h>
    #include<stdio.h>
    
    int dothings(char **k){
     printf("%c",*k);
    }
    
    int main(){
      char* c='h';
      dothings(&c);
    }

    and

    Code:
    #include<stdlib.h>
    #include<stdio.h>
    
    int dothings(char *k){
     printf("%c",*k);
    }
    
    int main(){
      char* c='h';
      dothings(&c);
    }
    The output is the same,but i dont understand why.Can you provide an example where the first occasion would be usefull.Thanks

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    In C, all parameters are passed by copying. To create a pass by reference, we use pointers or & (address of) operators - because an address, and a copy of that address, have exactly the same value. That is to say, whether I give you the note saying get the mail from mailbox 123, or I make a copy of that note with the mailbox address of 123, the net result is the same. You know to go to mailbox 123, either way.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Try compiling both programs with maximum warnings enabled. That will give you some insight into the differences.

    Both programs technically involve undefined behaviour, so explaining why they happen to produce the same results is pointless. The behaviour would be equally correct if they produced different results.

    The only value in both examples is demonstrating tricks to be avoided.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 10-30-2009, 04:41 PM
  2. char pointer to pointer question
    By Salt Shaker in forum C Programming
    Replies: 3
    Last Post: 01-10-2009, 11:59 AM
  3. Replies: 4
    Last Post: 08-27-2007, 11:51 PM
  4. pointer question.... pointer theory?
    By panfilero in forum C Programming
    Replies: 6
    Last Post: 11-12-2005, 02:29 AM
  5. pointer to pointer as argument question
    By Lateralus in forum C Programming
    Replies: 4
    Last Post: 07-21-2005, 05:03 PM

Tags for this Thread