txcotrader
txcotrader

Reputation: 595

c structure being passed into function

I am still learning C and had a question related to something I see fairly often. Please correct me if I'm wrong, is statement 1 the equivalent of statement 2?

  1. (struct sockaddr *) &echoServAddr
  2. struct sockaddr echoServAddr

If I understand this correctly, we are casting &echoServAddr to a struct framed the same as sockaddr.


So is the following code passing a struct by address?

/* Bind to the local address */
if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) {
    perror("bind() failed");
    exit(1);
} 

Upvotes: 0

Views: 116

Answers (2)

paulsm4
paulsm4

Reputation: 121799

// This declares a variable of type "struct sockaddr"
struct sockaddr echoServAddr;

// This merely takes a pointer to your structure,
// It (redundantly) casts that pointer to "struct sockaddr *" 
struct sockaddr *myPtr = (struct sockaddr *) &echoServAddr;

// This calls the function "bind()" and passes it a pointer to your structure
if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) {
    perror("bind() failed");
    exit(1);
} 

PS: Yes, you can cast one a pointer of one struct type to a pointer of a different struct type.

And unless the underlying struct's are in fact compatible, doing so could make you very Sad :)

Upvotes: 0

aragaer
aragaer

Reputation: 17858

Assuming these are both function arguments. These are different. First one is passing structure by reference. Second one is passing structure as is - the whole data is copied.

Bind accepts const struct sockaddr * as it's second argument, so that's correct code.

Upvotes: 1

Related Questions