C Pointer Question: Is It the Same?

  • Thread starter Thread starter James889
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 3K views
James889
Messages
190
Reaction score
1
Hello,

I have a question regarding pointers
Assume you have the following:

Code:
return &(((struct sockaddr_in*)sa)->sin_addr);

and
Code:
return &(struct sockaddr_in *)(sa->sin_addr);

Is this the same as writing &((struct sockaddr *)*sa).sin_addr)
and &(struct sockaddr *)(*sa.sin_addr)
?
 
Physics news on Phys.org
Play around and find out. seriously.

The top piece of code I do not believe is correct. sa I do not think is a socketaddr_in struct.. but it has been a while since i have done sockets.

But one is wrong, either the top or bottom, and I believe the top is wrong.

Now concerning your question, yes an no. you have some syntax problems. The first would work if you moved the deference away from sa.. actually both require it. you have to add another set of a parens .

&(*((struct sockaddr_in*)sa)).sin_addr; that should work.

and the bottom requires the deference for sa outside of the parens and that should work.

The issue is that doing it with void pointers or any data that has to be cast like that is it makes the code hard to read.

C is can be hard enough when you are reading poorly written and document code. there is no reason to make it worse.

No the valid use of that is if you were building an event driven system and built a matrix of event or state functions. And you wanted to call them on the fly. Or if you had a matrix of complex data.

That is about how C++ virtual tables work.