1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: C pointer question

  1. Sep 23, 2010 #1
    Hello,

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

    Code (Text):

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

    return &(struct sockaddr_in *)(sa->sin_addr);
     
    Is this the same as writing &((struct sockaddr *)*sa).sin_addr)
    and &(struct sockaddr *)(*sa.sin_addr)
    ?
     
  2. jcsd
  3. Sep 25, 2010 #2
    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.
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook