Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Assign Pointer to Pointer

Tags:

c++

pointers

#include <iostream>
using namespace std;

void fn(int* input_ptr) {
    int *ptr2 = input_ptr;
    cout << "pointer 2 is " << *ptr2 << endl;
}

int main() {
    int *ptr1;
    *ptr1 = 7;
    fn(ptr1);
}

This example works, as I pass a pointer to the function, and assign that to a temporary pointer inside the function, the result shows pointer 2 is also 7. However,

#include <iostream>
using namespace std;

int main() {
    int *ptr1;
    *ptr1 = 7;
    int *ptr2;
    *ptr2 = ptr1; // or I have also tried *ptr2 = *ptr1
    cout << "pointer 2 is " << *ptr2 << endl;
}

The same step does not work in the main function. I know you can use the address ptr2 = ptr1 without asterisk and it will work.

However, in the first example, I can directly assign a pointer as a function parameter to a new pointer with asterisk (or called dereferecing?), but in the second example I cannot do that in main function.

Could anyone help with this question? Appreciate your time.

like image 816
0xFF Avatar asked Dec 02 '25 13:12

0xFF


2 Answers

In both examples, you are dereferencing an uninitialized pointer, which is undefined behaviour.

For the pointer assignment question, you can directly assign:

 int *ptr2 = ptr2; 

in your second example, provided you make sure ptr1 points at a valid location. For example,

int x;
int *ptr1 = &x; /* ptr1 now points to the address of x */
*ptr1 = 7;
int *ptr2;
ptr1 = ptr2;
like image 120
P.P Avatar answered Dec 05 '25 02:12

P.P


In main, variable ptr1 is not initialized to point to a properly allocated block of memory.

Hence the rest of your program yields undefined behavior.

like image 37
barak manos Avatar answered Dec 05 '25 01:12

barak manos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!