Thread: functions and pointer arguments

  1. #1
    Unregistered
    Guest

    functions and pointer arguments

    Ok, i'm a bit confused with passing a pointer to a function e.g.

    void change_val(int *var, int val)
    {
    *var = val;
    }

    int main(void)
    {
    int a = 5;
    int *p = &a;

    p = &a;

    cout << "*p: " << *p << endl;

    change_val(p, 10);

    cout << "*p: " << *p << endl;

    return 0;
    }

    Most text i read say if you want to change the value of a pointer passed to a function you have to declare the parameter as a pointer to a pointer (int **var) and pass the pointer memory address (&p). So how does the above program work?

    Thanks for any help.

  2. #2
    Registered User
    Join Date
    Jan 2002
    Posts
    5
    OK, well, a pointer holds a memory address. I'm sure you know that. What you've done in the main function, is give the pointer, p, the memory address of a.

    So when you call the function change_val, you give the function a memory address, which is the memory address stored in p.

    What the program does, is uses the operator *, the dereferencing operator, and changes the memory at that address, not the pointer.

    And that's why the program works, since you're passing a memory address, and changing the data at that address. You're not changing the actual pointer.

  3. #3
    Unregistered
    Guest
    Ok, so when would i need to use int **ptr as a function parameter instead of just int *ptr?

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656

  5. #5
    Registered User
    Join Date
    Jan 2002
    Posts
    5
    If you wanted to change the actual pointer's memory address, you would use two * operators (**), showing that you want the memory address of a pointer.

  6. #6
    ¡Amo fútbol!
    Join Date
    Dec 2001
    Posts
    2,138
    why couldn't one just use the address of operater(&)

  7. #7
    Registered User
    Join Date
    Jan 2002
    Posts
    5
    I don't mean the pointer's memory address as in where it is stored the data is stored, but I mean the memory address it is pointing to.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  2. Problems passing a file pointer to functions
    By smitchell in forum C Programming
    Replies: 4
    Last Post: 09-30-2008, 02:29 PM
  3. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  4. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM