类型转换 void 指针到 int 时出现分段错误

Aqu*_*irl 2 c++ void void-pointers segmentation-fault

看到这个线程我写了以下内容:How do I conversion 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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

anisha@linux-dopx:~/> ./a.out 323

value: 
323
Segmentation fault
anisha@linux-dopx:~/>
Run Code Online (Sandbox Code Playgroud)

海湾合作委员会

我错过了什么?

Ale*_*lds 5

好吧,请忽略我之前的回答。请执行以下操作,而不是(char*)port - (char*)0

int h = *(int *)(&port);
Run Code Online (Sandbox Code Playgroud)

您得到的地址是port

&port
Run Code Online (Sandbox Code Playgroud)

将地址转换为int *

(int *)(&port)
Run Code Online (Sandbox Code Playgroud)

然后取消引用该地址以取回您放入的整数值port

*(int *)(&port)
Run Code Online (Sandbox Code Playgroud)