#include <iostream>
int main() {
// Write C code here
int *p = reinterpret_cast<int*>(50);
int q = 0;
q = *p;
std::cout << q;
return 0;
}
I want to assign a int * to the int. even if I am doing reinterpret casting to store in the int variable still showing segmentation fault. Please help me to fix this
CodePudding user response:
The problem is not the reinterpret_cast
, the problem is this line:
q = *p;
You try here dereference a pointer with address 50
which is an invalid address. If you want to assign the value of the pointer itself, you need to get rid of dereferencing operator *
and use one more reinterpret_cast
to cast pointer back to int
(or rather long int
).
But I have to agree with comments above: either you are just exploring how reinterpret_cast
works or you're probably doing something wrong (depends on what you want to achieve with this code).
CodePudding user response:
In the above code, I am assigning 50 as value to the pointer p but it is really store as a address of p. As @drescherjm said, I am trying to access invalid address in the next line. hence it is returning segmentation fault.
The actual answer to copy the int* to int is,
Blockquote
int s = 50; int *p = &s; int q = *p;