[英]Can someone explain this code with structs please? (trying to learn Winsock 2)
我经常看到形式的结构
struct Employee {
int age;
char* name;
}
我正在为Winsock 2看微软的“入门”,看到了这个:
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;
这是什么结构? 我认为结构的名称是addrinfo
,但是什么类型是*result
, *ptr
或hints
?
此外,如果以前从未编码过, hints
如何给出.ai_family/socktype/protocol
?
它是一种C风格的方式,将变量声明为结构的一个实例。 addrinfo
是在别处定义的结构, result
是指向一个实例的指针。 这是addrinfo的实际定义
在现代C ++中,以下内容是等效的:
addrinfo* result = NULL; // nullptr in C++11 and beyond
addrinfo* ptr = NULL; // nullptr in C++11 and beyond
addrinfo hints;
struct addrinfo
是包含网络地址信息的标准数据结构。 它由例如POSIX(又名SingleUnix )定义。 你可以通过包含netdb.h
或你的操作系统来获得它。 其领域(至少):
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
和ptr
是struct addrinfo
指针。 hints
是堆栈分配的struct addrinfo
。
Windows Socket API是纯C API,因此它使用C约定。 C中的结构变量必须用struct
声明。 你不能像在C ++中那样忽略struct
。 它们也没有初始化,因此memset()
^ W ZeroMemory()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.