-2
connect(socket_desc , (struct sock_address *)&server , sizeof(server)

why do we use * and & when trying to connect to a server or bind a server its like making a pointer or something but i believe that * doesn't make a pointer when combined with so why putting them both ? thanks for any answers.

1 Answers1

1
(struct sock_address *)&server

simply states: use the address of server, cast to a "pointer to sock_address structure".

You need to give the address because the function wants to change the things in that structure. And the cast is simply so it's the correct type.

It's not the same as:

int num = 42;
int num2 = *(&num); // num would be better.

which would be the two cancelling each other out.

While *ptr dereferences ptr to give you the underlying value, (type *)ptr instead treats ptr as if it was a pointer to type - there is no dereferencing in the latter case.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • so i cant do struct sock_address server ? – soldier captain May 03 '20 at 02:12
  • @soldiercaptain: in the UNIX world, you tend to have specific address types (like `sockaddr_in` for IP) but `connect` is meant to handle *all* types. The various `sockaddr_XX` types are cast to `sockaddr` so that `connect` gets a common type but `connect` itself is able to distinguish what type it is and act appropriately. Sort of a poor man's polymorphism :-) See https://stackoverflow.com/questions/21099041/why-do-we-cast-sockaddr-in-to-sockaddr-when-calling-bind for more detail. – paxdiablo May 03 '20 at 02:18