看到这个线程我写了以下内容:How do I convert from void * back to int
#include <iostream>
#include <stdlib.h>
using namespace std;
int main (int argc, char *argv[])
{
void* port = (void*) atoi (argv[1]);
cout << "\nvalue: \n" << atoi (argv[1]) << "\n";
int h = *((int *)port);
cout << h;
}
输出:
anisha@linux-dopx:~/> ./a.out 323
value:
323
Segmentation fault
anisha@linux-dopx:~/>
海湾合作委员会
我错过了什么?
最佳答案
好的,请无视我之前的回答。请执行以下操作,而不是 (char*)port - (char*)0
:
int h = *(int *)(&port);
您正在获取端口
的地址:
&port
将地址转换为 int *
:
(int *)(&port)
然后取消引用地址以取回您放入 port
的整数值:
*(int *)(&port)
关于c++ - 将 void 指针类型转换为 int 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8816034/