在下面的代码中,当我调用print vertex时,我没有明显的原因得到EXC_BAD_ACCESS
错误。指针指向完全相同的位置,但是当我传入vp2时,它会以某种方式崩溃。
#include <stdio.h>
typedef struct {
float x;
float y;
float z;
} Vertex;
void printVertex(Vertex *v);
int main (int argc, const char * argv[])
{
Vertex v = {1,0,2};
int memL = (int)&v;
Vertex *vp = &v;
printf("Memory Location: %i\n", memL);
printf("Memory Pointed to by Pointer: %i\n", (int)vp);
Vertex *vp2 = (Vertex *)memL;
printf("Memory Pointed to by Pointer from memory location: %i\n", (int)vp2);
printVertex(vp); // Executes normally
printVertex(vp2); // EXC_BAD_ACCESS
return 0;
}
void printVertex(Vertex *v)
{
printf("Vertex[%f,%f,%f]\n", v->x, v->y, v->z); // EXC_BAD_ACCESS when vp2 passed in
}
输出:
Memory Location: 1606416816
Memory Pointed to by Pointer: 1606416816
Memory Pointed to by Pointer from memory location: 1606416816
Vertex[1.000000,0.000000,2.000000]
EXC_BAD_ACCESS Error
答案 0 :(得分:2)
int memL = (int)&v;
可能会截断v
的地址。你可以尝试:
intptr_t memL = (intptr_t)&v;
看看是否是这种情况。如果截断是一个问题,这不应该崩溃。
答案 1 :(得分:1)
您的指针是64位宽,但您的int
类型只有32位宽。你扔掉了一半的指针信息!