galah92 galah92 - 3 months ago 6
C++ Question

Change a pointer to int passed to function

Considering the following code (basic C++):

#include <cstdio>

void changeNum(int* n) {
int x = 6;
n = &x;
}

int main() {
int num = 5;
changeNum(&num);
printf("num = %d\n", num);
}


Why
num
is still 5? Shouldn't
n = &x
make it 6?

Does
x
get deleted when exiting the function?

Answer

Does x get deleted when exiting the function?

Yes. x is a local variable. Those variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code.

In short, that means when the function changeNum ends, the variable x (which is allocated on the stack) will be destroyed.

Why num is still 5? Shouldn't n = &x make it 6?

Let's analyse your strange function:

void changeNum(int* n) {
    int x = 6;
    n = &x;
}

What you're doing here is create a pointer n and assign to it the address of the local variable x.

Various comment are wrong, pay attention! That is no an undefined behaviour. The pointer n is created (since passed by value, note the pointer itself is passed by value!) when the function is invoked and it's destroyed when the function ends.

Practically your function does nothing: create a pointer, which is initialized with an address provided by the caller, and assign to it another address.

changeNum(&num);

Just says: "create a temporary pointer, pass it by value to the function changeNum (note pass by value the pointer!)". So it will create a copy of the pointer and used by the function.

How can I achieve what I want?

I suggest you to study better, because your code shows your inexperience with the pointers.

Anyway the right behaviour it should be:

void changeNum(int* n) {
    *n = 6
}

Which assigns 6 to the integer pointed by n!

Comments