#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.
This example works,- You are just lucky.ptr1is not given memory address to point to. You need to usenewto allocate memory