n
is a pointer that is being passed by value, so any modifications made by the function to the pointer itself are not applied to the caller's variable. And as such, you are leaking memory since you are new
'ing memory that you are not able to delete
afterwards.
To do what you are attempting, you need to pass n
by reference instead:
void foo(int* &n) {
n = new int;
*n = 11;
// or simply:
// n = new int(11);
}
Otherwise, you should change your function to return
the new pointer instead of outputting it via a reference parameter:
#include <iostream>
int* foo() {
int *n = new int;
*n = 11;
return n;
// or simply:
// return new int(11);
}
int main() {
int *num = foo();
std::cout << num << '\n';
delete num;
return 0;
}
That being said, in C++11 and later, you should be using std::unique_ptr
instead of a raw pointer:
#include <iostream>
#include <memory>
void foo(std::unique_ptr<int> &n) {
n.reset(new int(11));
// or:
// std::unique_ptr<int>(new int(11)).swap(n);
// or, in C++14 and later:
// n = std::make_unique<int>(11);
}
int main() {
std::unique_ptr<int> num;
foo(num);
std::cout << num.get() << '\n';
return 0;
}
#include <iostream>
#include <memory>
std::unique_ptr<int> foo() {
return std::unique_ptr<int>(new int(11));
// or, in C++14 and later...
// return std::make_unique<int>(11);
}
int main() {
std::unique_ptr<int> num = foo();
std::cout << num.get() << '\n';
return 0;
}