I am calling the following library function in two ways:
unsigned int
LsSendToQ(unsigned int p4Node, const char queueName[4], lsMsg *pMsg,
unsigned int prio) {
}
The first way :
LsSendToQ((unsigned int)0, (const char *)Q_NAME, (lsMsg *)(void *)pMsg, 0)
and the second way :
LsSendToQ((unsigned int)0, (const char *)Q_NAME, (lsMsg *)pMsg, 0)
Both calls compile fine, but which one is the right way ? And why is (void *)
used in the first call, which looks like a function pointer to me ?
A pointer to void
is a "generic" pointer type. A void *
can be converted to any other pointer type without an explicit cast. You cannot dereference a void *
or do pointer arithmetic with it; you must convert it to a pointer to an complete data type first. See this answer.
So the parameter pMsg
is not directly compitable to lsMsg * then the 2nd calling is a possible way to use this in the function calling[ I didn't tested it].
By the way, as long as type of pMsg
is lsMsg *
the 1st one is enough.
Edit:
The 2nd one is enough as it covers the 1st one.
The second version is the correct one.
The first call looks like an attempt to dodge incompatible type warnings. If pMsg
is not compatible with lsMsg *
you could kill the compiler warning by casting to void*
in between.
You shouldn't do this though, because it almost certainly hides a bug in your program! Either the two pointer types are completely incompatible, in which case the program may instantly crash & burn upon accessing the pointer. Or they are in theory compatible, but the compiler implements type aliasing and the (void*)
cast would then hide a violation of the "strict aliasing rule". In either case you have undefined behavior and a severe bug.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With