我仍然是C的菜鸟.我经常使用它,但通常不使用C的指针功能.我要做的是将指针传递给函数内局部空间中已经存在的结构.我有这个代码:
struct WorldCamera p_viewer;
struct Point3D_LLA p_subj;
struct Point2D_CalcRes p_res;
p_viewer.hfov = 25;
p_viewer.vfov = 25;
p_viewer.p.lat = 10.0f;
p_viewer.p.lon = 10.0f;
p_viewer.p.alt = 100.0f;
p_subj.lat = 9.98f;
p_subj.lon = 10.0f;
p_subj.alt = 100.0f;
// Do something interesting here.
compute_3d_transform(&p_viewer, &p_subj, &p_res, 10000.0f);
// Do something interesting here.
Run Code Online (Sandbox Code Playgroud)
compute_3d_transform的原型是这样的:
void compute_3d_transform(struct WorldCamera *p_viewer, struct Point3D_LLA *p_subj, struct Point2D_CalcRes *res, float cliph);
Run Code Online (Sandbox Code Playgroud)
我想知道我是否做对了.我正在一个小型微控制器上编程,我认为它没有太大的内存保护.破坏一块内存可能会导致将来出现奇怪的错误,这些错误很难调试.我试图避免使用malloc/calloc函数,因为这些需要专用堆.
使用addressof运算符&.
啊,你是对的.
你拥有它的原因是,例如,&p_viewer是一个指向(对于你的例子,本地)变量的指针p_viewer,它是一个struct WorldCamera.并且compute_3d_transform想要指向a的指针struct WorldCamera,因此您作为调用者的意图与被调用者的意图相匹配.
当然,没有看到整个意图(只能通过阅读程序,包括compute_3d_transform或至少其文档来收集),可能存在逻辑错误,但是类型匹配的事实已经非常舒适(当然,如果类型void *相反,那么有更多的麻烦,因为意图不是那么清楚)