我知道这可能是一个初学者的问题,但是无论我如何搜索或排列代码,都似乎没有解决。
我有一个定义如下的结构。
typedef struct
{
int rate;
int duration;
} DummyStructure;
现在,我尝试使用类似于以下代码的内容。
//
DummyStructure* structure;
DummyStructure* structure2;
long int point;
//
structure = (DummyStructure*)malloc(sizeof(DummyStructure));
structure->rate = 19;
structure->duration = 92;
point = (long int)&structure;
// now i'd like to set structure2 to the same memory location as 1.
// point is the 8-byte int location (i assume?) of structure.
// so naturally i'd assume that by casting as a DummyStructure pointer
// that long int would act as a pointer to that 1.
// It doesn't.
structure2 = (DummyStructure*)point;
我强调我已经尝试了所有可能的**和*的排列组合,但是我就是搞不定。要么它无法编译,要么它可以编译,但当我使用structure2中包含的字段时,我最终得到的似乎是随机数字。我认为我以某种方式获得了不正确的内存位置,但除了使用&之外,还能怎么样才能得到呢?
我有内存位置,对吗?我该如何将结构设置为该位置?
编辑;我忘记提到(后续答案已经询问),但我的目的是使用此功能来包装jni的libvorbis。使用jni意味着我无法传回libvorbis所做的任何结构,但它需要这些结构作为其核心功能。因此,我的包装器将直接使用vorbis来创建这些结构,并将它们的指针传回给java,以便在需要用更多声音填充缓冲区时,我只需要从指针的整数值重新引用结构对象。
malloc(3)
的返回值强制转换--只需#include <stdlib.h>
,您将获得允许编译器为您处理一切的malloc(3)
原型。这些强制转换可能会隐藏编译器警告消息,这些消息会提醒您代码中的错误。 - sarnoldlong
不足以容纳指针值。 使用(u)intptr_t
,size_t
, 或long long
可能会得到更好的结果。 - Alexey FrunzeDummyStructure**
可以很好地工作。 - Dan