C Pointer Question: Is It the Same?

  • Thread starter Thread starter James889
  • Start date Start date
AI Thread Summary
The discussion revolves around the correct usage of pointers in C, specifically regarding the dereferencing and casting of a `struct sockaddr_in`. One participant questions the validity of two code snippets that aim to return the address of `sin_addr`. It is suggested that both snippets have syntax issues, particularly with the placement of dereferencing operators. The conversation emphasizes the importance of code readability, especially when dealing with complex pointer manipulations. Ultimately, clarity in pointer usage is crucial for maintaining understandable C code.
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.
 

Similar threads

Back
Top