pass by reference and pointers

Lets say I have a function

foo(bar &t)
{
//code
}

and in main I have

main()
{
bar *t;
foo(*t);//version that works
foo(t); //compile error
}

when i call foo(*t), is the program making a copy of the value pointed to by t and then passing the address to foo, or does it just pass the address of the value pointed to by t?
Err, you're trying to send a pointer by reference, and not by value.

But a pointer already holds a reference.

foo(t); doesn't work since pointers are essentially variables that hold adresses (or references, if you will) in memory.

I may be wrong though.

Pointer to a pointer maybe? ;)

You know you can use pointers in parameters aswell, foo(bar *t)
Last edited on
smilodon wrote:
when i call foo(*t), is the program making a copy of the value pointed to by t and then passing the address to foo, or does it just pass the address of the value pointed to by t?

The latter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

void foo(int &i)
{
    i=10;
}

int main()
{
    int a=5;
    int * pa=&a;

    foo(*pa);

    cout << a << endl;

    cin.get();
    return 0;
}
@m4ster r0shi, just making sure, you could just do

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

void foo(int &i)
{
    i=10;
}

int main()
{
    int a=5;
    foo(a)

    cout << a << endl;

    cin.get();
    return 0;
}


without bothering with the pointer, right?
Right.
Ok, thank you.
Topic archived. No new replies allowed.