How to change the value of an argument, in a function?

Hello, the Question goes like this::

A function update_pointer takes a format argument called p of type int* and must change the value of this argument. Provide two possible ways in which the function may be defined. For each way, show the header of the function and how it should be invoked to change the value of
an actual argument called ptr.

ok, so my answer is this:
1)
1
2
3
void update_pointer(int *&p); // header declaration

update_pointer(p) // to invoke the function. 


i can't think of any other way, any hint?
closed account (3pj6b7Xj)
Hmm int * &p, I've never seen that a function that passes a pointer to a reference? or a reference to a pointer?

1
2
3
4
5
6
7
8
9

int number =28;
int * pnumber = &number;
update_pointer(pnumber);

void update_pointer(int * p)
{
     p->10;
}


I could be wrong, I have not done this type in a while.
Last edited on
You cannot get the address of a reference.
Check this out:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;

void update_int1(int & int_ref) { int_ref=5; }
void update_int2(int * int_ptr) { *int_ptr=10; }

void update_int_ptr1(int * & int_ptr_ref) { int_ptr_ref=(int*)0xff; }
void update_int_ptr2( /*...*/ ) { /*...*/ }

int main()
{
    int n=0;
    int * p=(int*)0x11;

    cout << "n=" << n << endl;

    //update a number using a reference
    update_int1(n);
    cout << "n=" << n << endl;

    //update a number using a pointer
    update_int2(&n);
    cout << "n=" << n << endl;

    cout << "p=" << p << endl;

    //update a pointer using a reference
    update_int_ptr1(p);
    cout << "p=" << p << endl;

    //update a pointer using a ...
    //...

    return 0;
}
What is the other way to update a pointer?
A pointer...

1
2
3
4
5
6
7
8
9
10
11
12
//...

void update_int_ptr2(int * * int_ptr_ptr) { *int_ptr_ptr=(int*)0xab; }

//...

    //update a pointer using a pointer
    update_int_ptr2(&p);
    cout << "p=" << p << endl;

    return 0;
}

p = update(p);
M4ster r0shi, thanks so much, exact question was on the final exam paper (today).
closed account (3pj6b7Xj)
good stuff, good stuff. C++ code just looks so elegant :)
mrfaosfx wrote:
Hmm int * &p, I've never seen that a function that passes a pointer to a reference? or a reference to a pointer?
It's a refenrence to a pointer (and is perfectly ok in C++) so you can manipulate the pointer without having a pointer to a pointer.


rocketboy9000 wrote:
You cannot get the address of a reference.
You can.
1
2
3
4
void update_pointer(int *&p)
{
  int **x = &p; // the pointer to the pointer
}
is ok in C++
NO, in fact you cannot.
1
2
3
int i;
int &r=i;
&r == &i;

Because references are treated like aliases, &r gives you the address of the referent object i.
@ rocketboy9000

ok, now I see what you mean
Topic archived. No new replies allowed.