Pointers in C and how to pass local variables as pointers
I'm still a noob to C. I use it on a regular basis, but generally don't use the pointer features of C. What I'm trying to do is pass pointers to structures that already exist in local space inside a function. I have this code:
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.
The prototype of compute_3d_transform is this:
void compute_3d_transform(struct WorldCamera *p_viewer, struct Po开发者_开发知识库int3D_LLA *p_subj, struct Point2D_CalcRes *res, float cliph);
I want to know if I've got this right. I am programming on a small microcontroller which I don't think has much memory protection. Corrupting one piece of memory could cause odd bugs in future which would be very difficult to debug. I'm trying to avoid the use of the malloc/calloc function as these require a dedicated heap.
Use the addressof operator &
.
Ah yes you have it right.
The reason why you have it right is that, for e.g., &p_viewer
is a pointer that points to the (for your example, local) variable p_viewer
, which is a struct WorldCamera
. And compute_3d_transform
wants the a pointer to a struct WorldCamera
, so your intentions as a caller match the intentions of the callee.
Of course, without seeing the whole intention (which can only be gleaned by reading the program, including compute_3d_transform
, or at least its documentation), there might a logic error, but the fact that the types match up is already of great comfort (of course, if the type were void *
instead then there are more headaches because the intention is not so clear)
I'm guessing your compute_3d_transform
function writes its result into p_res
-- if that's all it does, your code is fine.
Just make sure you don't store pointers to local variables elsewhere such that they could possibly be used after the variables go out of scope.
Your code is correct, and memory corruption is unlikely.
The thing to mind is any side effects of functions you are passing pointers to. Especially with pointers to stack allocated data, those pointers should be considered invalid once you return from the function that contained the data.
It all comes down to knowing what's happening with your pointers. The compute_3d_transform
function likely uses the viewer and subject parameters as input, and fills the area the result parameter points to. It doesn't store the pointers, so they might be used later, so there are no side-effects after compute_3d_transform
has completed. (Pointer parameters that are used as input only are usually marked const
, to mark the target area as constant for the purposes of that function.)
精彩评论