Let me elaborate,
If I pass a pointer by reference using a function, and that function then assigns a new object to it, is there a way for that object to remain in memory after the program exits the function.
Heres an example of what i mean: (the program always outputs NULL)
#include <iostream>
using namespace std;
void assign_int(int *a) { //<-- assigns some number to the pointer
a = new int;
*a = 5;
}
int main() {
int *a = NULL;
assign_int(a);
if(a == NULL) {cout << "NULL";} //<-- checks whether or not the number is there.
else {cout << *a;}
}
I've been working on an implementation of a linked list using pointers and nodes (each node consisting of a number and a pointer) but as soon as I leave the function that creates the list all of the new nodes get deleted, and the list becomes empty.
I understand that local variables get deleted as soon as they leave the scope they've been declared in, but is there a way to avoid this?