Thread: Set a value to a pointer in a function

  1. #1
    Registered User
    Join Date
    Dec 2010
    Posts
    71

    Set a value to a pointer in a function

    Code:
    int main()
    {
        int *f;
        set(f);
        printf("%d",*f);
        return 0;
    }
    void set(int *f)
    {
        int d=11;
        f=&d;
    }
    Why it does not work?"It printf" value 0.
    d is deleted at the end of function?(I still have lower concerns on dynamic allocation).
    I need to create an ordered binary tree.
    Last edited by nutzu2010; 12-23-2011 at 02:32 PM.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    You're passing the pointer by value. You can change what it points to, but any change of its value is local to the function.

    Even if you fix that, d (inside set()) will not exist either, so printing *f in main() would give undefined behaviour.

    Try this
    Code:
    int main()
    {
        int *f;
        set(&f);
        printf("%d",*f);
        return 0;
    }
    void set(int **f)
    {
        static int d=11;    /*  One way of ensuring d continues to exist when set() returns */
        *f=&d;
    }
    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.

  3. #3
    Registered User
    Join Date
    Dec 2010
    Posts
    71
    So,to create a binary search tree must declare a static node or return the node new created like this?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. passing method pointer as a function pointer
    By sevcsik in forum C++ Programming
    Replies: 5
    Last Post: 12-30-2007, 06:19 AM
  2. Replies: 7
    Last Post: 07-04-2007, 12:46 PM
  3. Replies: 9
    Last Post: 01-02-2007, 04:22 PM
  4. Replies: 4
    Last Post: 11-05-2006, 02:57 PM
  5. Replies: 6
    Last Post: 11-29-2004, 08:50 AM