csockets

Meaning of "&(sockaddr_in.sin_addr)" expression


There's a nice answer to the problem of converting IP address to string representation and back.

I mean specifically this snippet:

struct sockaddr_in sa;
char str[INET_ADDRSTRLEN];

// store this IP address in sa:
inet_pton(AF_INET, "192.0.2.33", &(sa.sin_addr));

Ampersand is obviously address of a variable. However, what I don't get is why parentheses are needed in &(sa.sin_addr)? Intuitively I think of following expression as address of sin_addr: &sa.sin_addr.

Does such expression in C actually mean address of sa rather than sin_addr of the sin_addr field? Why the parentheses are here and what effect do they have?


Solution

  • The parentheses are not required in this case.

    The member access operator . has higher precedence than the address-of operator &. So whether or not the parentheses are present has no effect.

    Here's the relevant subset of those precedence rules:

    Precedence Operator Description
    1 . Structure and union member access
    2 & Address of