[英]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.