function argument of type pointer

Hello everyone.
I have to write an example in which you use a function having as argument a pointer passed by reference in C++.
Can you provide an example like this:
funz.h : void funz( int *&a );
funz.cpp : ? (1)
main.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "funz.h"
#include <iostream>

using namespace std;

int main()
{
  int b = 10;
  cout << "Before of funz(), b = " << b << endl;
  funz(?);    // (2)
  cout << "After of funz(), b = " << b << endl;
  return 0;
}

as I write in (1) and (2) ?
Last edited on
void funz( int *&a ); wat? *&a is gibberish, I wouldn't be surprised if it failed to compile. int *a means that a is a pointer (or, *a is an int).

(1)
1
2
3
4
void funz( int *a )
{
    // code that uses a
}


(2) use & to get the address of a variable, &b is the address of (aka a pointer to) b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

void funz( int*& a )
{
    static int b = 45 ;
    a = &b ;
}

int main()
{
    int i = 777 ;
    int* pi = &i ;
    std::cout << "int at address " << pi << " has value " << *pi << '\n' ;
    
    funz(pi) ;
    std::cout << "int at address " << pi << " has value " << *pi << '\n' ;
}

http://coliru.stacked-crooked.com/a/4cad00f30b705416
void funz( int *&a ); wat? *&a is gibberish, I wouldn't be surprised if it failed to compile.

Um, no. It's exactly what the OP said it was - a reference to an int*. A pointer is a data type like any other, and you can have references to them like any other type.

To the OP, an example might be a function which allocates some memory, and returns the pointer to that newly-allocated memory as an argument, by reference.
Thanks MikeyBoy, Lachlan Easton, JLBorges. I found the solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "funz.h"

void funz( int *&a )
{
    *a += 1;

    return;
}

#include <iostream>
#include "funz.h"

using namespace std;

int main()
{
    int c = 10;
    int *b = &c;
    cout << "Prima di funz(), *b = " << *b << endl;
    funz(b);
    cout << "Dopo di funz(), *b = " << *b << endl;
    return 0;
}

That's nice, but it doesn't demonstrate that you're passing the pointer by reference. To demonstrate that, you want your function to change the value of the actual pointer, b, itself - not the value stored in the memory it's pointing to.

Last edited on
Topic archived. No new replies allowed.