开发者

What should be the correct way to assign a value to a non-empty void* pointer in C?

I've the following code:

void funcA(void*   pArg)
{
    STRUCTA abc;
    .
    . // Some processing here
    .

    if (pArg)
       (STRUCTA *)pArg = abc;
}

the problem is, this code is throwing up the following warning: warning: target of assignment not really an lvalue; this will be a hard error in the future

Without the cast, I'll get another warning that I'm trying to dereference a void pointer...

As warnings are being treated as errors, I can't use this code - But I really can't use any other pointer type than void* as t开发者_开发技巧he argument. Is there an elegant solution I'm missing?

Is there any way to make this work?


(STRUCTA *)pArg is of pointer type, while abc isn't. You need to dereference the pointer:

*(STRUCTA *)pArg = abc;


You are assigning a STRUCTA to a pointer to STRUCTA.

Rather do:

*((STRUCTA *)pArg) = abc;


Try this:

memcpy(pArg, &abc, sizeof(abc));

However you must make sure that pArg points to sizeof(abc) bytes of allocated memory.


Maybe pArg = (void *) abc; ?

EDIT:

pArg = (void *) (&abc); ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜