c - 如何正确地从 int 的内容创建指针?

标签 c pointers

<分区>

由于各种限制,我有一个方法只接受 int争论。但是,我想将结构传递给此方法。

到目前为止,我已经...

main(int argc, char* argv){
    Somestructure * name;
    //Name is malloced, things are put in it, etc.

    int address = (int) &name;
    method(address);
}

void method(int arg){
     Somestructure* thisStruct = (Somestructure*) arg;
     //Do stuff with thisStruct.
}

我认为这会分配 thisStruct指向与 main 方法中的名称相同的结构,但是当我尝试使用 thisStruct 时在method ,我得到一个总线错误。 当我使用这段代码时...

    int structAddress = (int) &thisStruct;
    printf("[Method] Address : %d\n", structAddress);

好像地址是name (在 main 内)和 thisStruct 的(在 method 内)不同。

我对 C 有点陌生,但是,有人知道这里发生了什么吗?

此代码只能在 32 位系统上运行,因此我不必担心任何 64 位 int/地址问题。

最佳答案

你的问题是你传入了&name,它是一个指向struct的指针。因此,在方法中,您正在访问Somestructure **,就好像它是一个Somestructure *

只需传入(int)name即可。

(附:定义“通用参数”的常用方法是使用 void *。)

关于c - 如何正确地从 int 的内容创建指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14704940/

相关文章:

c++ - 如何查看我发送的流 libvlc C/C++

c++ - 如何从 const float* 中获取 C++ vector

c - 指针算术和导航 malloc 数组

c - 使用 atoi() 对整数进行输入验证

c - IUP 拆分溢出对话框?

c - 如何从 32 位 float 中提取符号、尾数和指数

c++ - 函数声明中的 `*&` 是什么意思?

c++ - 指针内存使用

c - 任何优化都会删除代码(指向数组的 volatile 指针)

c++ - 在 C++ 中使用文件句柄的条件