0
Pointers & Memory Location.
#include <iostream> using namespace std; int main() { int num1 = 50, *num2 = &num1; cout << *num2 << endl; //This prints out 50 cout << num2; // This prints out a hexadecimal. return 0; } Question: Why does the code run this way? Isn’t num2 supposed to equal the value stored in the memory for num1 while *num2 equals the address as stated in the code ?
1 Respuesta
0
When you declared this line:
int *num2 = &num1;
You assigned num2 as the address of num1. Notice the difference:
// declaration of pointer
// num2 is now address of num1
// num2 = &num1
int *num2 = &num1
// num2 is now address of num3
num2 = &num3
// dereferencing pointer
// prints num3
cout << *num2;
Anyway, your confusion might be because of the declaration. You can instead write it this way:
// declare (int*) with name num1
int* num1 = &num2