Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these two C function calls?

Tags:

c

linux

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 ?

like image 353
dexterous Avatar asked Feb 08 '23 00:02

dexterous


2 Answers

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 pMsgis 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.

like image 131
Shafi Avatar answered Feb 28 '23 07:02

Shafi


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.

like image 37
Lundin Avatar answered Feb 28 '23 07:02

Lundin