I recently got curious about pointers and I cannot understand why the following doesn't work.
My idea is to create a variable, say its address (in decimal), ask the user to input it back and take that as the address for a pointer which points to the previous variable. In the end both variables should have the same value.
The last pointer points to supposedly, a bad memory address because it segfaults, but when I print the address of the pointers they are the same!
#include <iostream>
int main() {
int temp = 0;
printf("Temporary integer addr 0x%x (dec %d)\n", &temp, &temp);
int input = -1;
printf("Give me an address to read (in dec)\n");
std::cin >> input;
printf("You chose the number %d (hex 0x%x)\n", input, input);
int* intPtr = (int*)input;
int* tempPtr = &temp;
if (intPtr == tempPtr) {
printf("It works, they are equal!\n");
} else {
printf("Expected: 0x%x got 0x%x\n", tempPtr, intPtr);
printf("Expected value: 0x%d got 0x%d", temp, *intPtr); // segfaults
}
return 0;
}
And this is the console output
Main function addr 0xb0ddf7d0 (dec -1327630384)
Temporary integer addr 0xb0ddf7c8 (dec -1327630392)
Give me an address to read (in dec)
-1327630392
You chose the number -1327630392 (hex 0xb0ddf7c8)
Expected: 0xb0ddf7c8 got 0xb0ddf7c8
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
What is wrong with it? How can I create a pointer that points to the address the user inputs? I compiled it on g++ (GCC) 8.2.1 20181127