Set a value to a pointer in a function

This is a discussion on Set a value to a pointer in a function within the C Programming forums, part of the General Programming Boards category; Code: int main() { int *f; set(f); printf("%d",*f); return 0; } void set(int *f) { int d=11; f=&d; } Why ...

  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 01:32 PM.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,163
    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%.

  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, 05:19 AM
  2. Replies: 7
    Last Post: 07-04-2007, 12:46 PM
  3. Replies: 9
    Last Post: 01-02-2007, 03:22 PM
  4. Replies: 4
    Last Post: 11-05-2006, 01:57 PM
  5. Replies: 6
    Last Post: 11-29-2004, 07:50 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21