2
#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.

1
  • 4
    This example works, - You are just lucky. ptr1 is not given memory address to point to. You need to use new to allocate memory Commented Nov 6, 2016 at 14:15

3 Answers 3

11

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; 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your time and help. I have one more question, int *ptr1 = &x; is equal to int *ptr1; ptr1 = &x; right?
5

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.

Comments

1

There's a major problem with how you are using pointers here. Directly dereferencing a pointer can cause undefined behavior as suggested by usr and barak

You need to allocate memory for the pointer here using

int* ptr1 = new int[1]; 

Also since you're the one allocating memory, you need to clean up before exiting with

delete[] ptr1; 

In case you don't wish to work with Dynamic Memory allocation, you could initialize it as

int a = 7; int* ptr1 = &a; 

This way you won't be dereferencing stray pointers and causing undefined behavior.

Regarding your output with

 *ptr1 = ptr2; // or I have also tried *ptr1 = *ptr2 

Assignment of values in C++ or C is from right to left. Hence ptr2 won't have the values of ptr1;

For example;

int a = 5; int b = 6; a=b; 

would make a = 6.

Conversely

b = a; 

would make b = 5.

1 Comment

Instead of int* ptr1 = new int[1]; you could use new int

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.