I have typically seen structs of the form
struct Employee {
int age;
char* name;
}
I was looking at Microsoft's "Getting Started" for Winsock 2, and saw this:
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
What kind of struct is this? I figure the name of the struct is addrinfo
, but then what type are *result
, *ptr
, or hints
?
Also, how is hints
given a .ai_family/socktype/protocol
when it never was coded previously?
It's a C-style way of declaring a variable as an instance of a struct. addrinfo
is the struct that's defined elsewhere, and result
is a pointer to an instance of one. Here is the actual definition of addrinfo
In modern C++, the following is equivalent:
addrinfo* result = NULL; // nullptr in C++11 and beyond
addrinfo* ptr = NULL; // nullptr in C++11 and beyond
addrinfo hints;
struct addrinfo
is a standard data structure to contain network address information. It is defined by eg POSIX, aka SingleUnix . You get it by including netdb.h
or your OS' equivalent. Its fields are (at least):
int ai_flags Input flags.
int ai_family Address family of socket.
int ai_socktype Socket type.
int ai_protocol Protocol of socket.
socklen_t ai_addrlen Length of socket address.
struct sockaddr *ai_addr Socket address of socket.
char *ai_canonname Canonical name of service location.
struct addrinfo *ai_next Pointer to next in list.
struct addrinfo *result = NULL, *ptr = NULL, hints;
result
and ptr
are pointers to struct addrinfo
. hints
is a stack-allocated struct addrinfo
.
The Windows Socket API is a pure C API hence it uses C conventions. Structure variables in C must be declared explictly with struct
. You cannot leave off the struct
as in C++. They are also not initialized, hence the memset()
^W ZeroMemory()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.