c++ - 将 void 指针类型转换为 int 时出现段错误

标签 c++ segmentation-fault void void-pointers

看到这个线程我写了以下内容: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/

相关文章:

c++ - 如何让一个程序在其他电脑上运行?

iphone - @try @catch 是否适用于 SIGSEGV/SEGV_ACCERR

java - 为什么我的按钮在 Android Studio 中不起作用?

c - 理解 C 中的 pthread_create 参数

c++ - 减少 Linux 中的每个线程内存

c++ - 写入文件时出现堆损坏

c++ - 如何为 PerfPublisher 插件生成 xml dtd 报告以在 jenkins 上可视化?

c - C中这个指针程序中的段错误

c - 读取 PPM 时出现段错误

c - 当我们将返回类型为 void 的函数调用返回值分配给 int 变量时会发生什么?