在下面的代碼中,當我打印頂點時,我得到一個EXC_BAD_ACCESS
錯誤,沒有明顯的原因。指針指向完全相同的位置,但不知何故,當我通過vp2時它崩潰。爲什麼在通過int投射後獲得EXC_BAD_ACCESS?
#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
使用'%p'打印intptr_t的指針 – 2012-03-06 01:29:35