1

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?

leo
  • 31
  • 4

2 Answers2

3

In your function assign_int, a is a function local variable. Any changes to it does not affect the value of the the variable in the calling function.

The issue is more cleary understood with a simpler type of object.

void foo(int i)
{
   i = 10; // This changes the local variable's value.
}

int main()
{
   int i = 20;
   foo(i);

   // Value of i is still 20 in this function.
}

If you want to see the changes made to i in foo to be reflected in main, you'll have to accept the variable by reference.

void foo(int& i)
{
   i = 10; // This changes the value of the variable in the calling function too.
}

Pointers are no different.

void assign_int(int *a) {
    a = new int;  // This changes the local variable's value.
    *a = 5;       // This changes the value of object the local variable points to
}

To see the new value of a and the object it points to, assign_int has to accept the pointer by reference.

void assign_int(int*& a) {
    a = new int;  // This changes the value of the variable in the calling function too.
    *a = 5;       // The value of the object the pointer points to will be visible in 
                  // the calling function.
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • ooh, so the function I used actually created a duplicate pointer, and the duplicate was the one assigned to the number. I see the problem now, thank you :] – leo Jun 06 '19 at 21:24
  • @leo, you're welcolme. Glad I was able to help. – R Sahu Jun 06 '19 at 21:29
2

You need extra indirection, as with reference:

void assign_int(int *&a) {
    a = new int;
    *a = 5;
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • 1
    But it is highly unlikely you want to do this, rather than returning the pointer via the function's return value. –  Jun 06 '19 at 21:02
  • Oh, that solved it. I feel really dumb now .-. – leo Jun 06 '19 at 21:04