Pointers C++
Hello I am trying to fix this piece of code here.
1 2 3
|
int num1 = 100;
int &num2;
*num2 = num1;
|
but whenever I try to cout num2 I get 0096FEE0.
I think in this code, you are supposed to swap num1 and num2 with pointers.
Here's what I so far.
1 2 3 4 5 6 7 8
|
int num1 = 100;
cout << "num1: " << num1 << "\n";
int *num2 = & num1;
*num2 = 100;
cout << "num2: " << num2;
return 0;
|
surprised this compiles. You've declared num2 as a reference, not as a pointer.
for your first snippet, use this:
1 2 3
|
int num1 = 100;
int* num2;
*num2 = num1;
|
For your second piece, do this:
1 2 3 4 5
|
int num1 = 100; // int num1 gets 100
cout << "num1: " << num1 << "\n"; // print num1
int* num2 = &num1; // pointer-to-int num2 gets address of num1
*num2 = 100; // value at num2 gets 100
cout << "num2: " << *num2; // print value at num2
|
You were printing the address of num2, not the value.
1 2 3
|
int* num2 // declare a pointer num2
*num2 // Value at num2
&num1 // Address of num1;
|
Last edited on
You were printing the address of num2 |
No. He/she was printing out the address of where num2 is pointing to :)
Topic archived. No new replies allowed.