inet_ntop() 的簽名如下:
const char* inet_ntop(int af, const void* src, char* dst, socklen_t size);
描述:
This function converts the network address structure src in the
af address family into a character string. The resulting string
is copied to the buffer pointed to by dst, which must be a non-
null pointer. The caller specifies the number of bytes available
in this buffer in the argument size.
On success, inet_ntop() returns a non-null pointer to dst, or NULL
if there was an error.
套接字操作的模式(例如,getsockopt()、socket()、bind()、listen()、connect() 等)通常回傳一個 int,表示 (0) 成功或 (-1) 錯誤.
對于 inet_ntop() 來說,回傳一個指向呼叫者傳遞給它的資料結構的指標似乎是多余的——dst。顯然,呼叫者已經知道該資料,因為需要將其傳遞給函式。這必須有一些令人信服的理由才能脫離公約;回傳冗余資訊肯定不能這樣。
只是沒有看到原因,我感到很愚蠢。有什么見解嗎?
uj5u.com熱心網友回復:
雖然這些選擇的原因應該在委員會討論的記錄中找到,或者詢問設計 API 的人,我可以猜測一下。
inet_ntop()是一個 POSIX 函式,所以它來自 C 而不是來自 C 。正如您所說,套接字操作的模式是回傳一個int. 但inet_ntop()它更像是一個字串函式,所以我會將它與string.h庫中的函式進行比較。只考慮
char *strcpy( char *dest, const char *src );
為什么回傳我傳入的相同指標?對于不宣告多個臨時變數的鏈接操作:
char s[] = "this is the origial string I want to copy";
char *my_copy = strcpy(malloc(strlen(s) 1), s);
(我知道這是不好的做法,因為我們沒有檢查 的回傳值malloc,但我認為設計沒有考慮到這一點)。
更多(真的更多)猜測作業可以在這里找到。
uj5u.com熱心網友回復:
如果您想減少代碼行數,這很有用。您可以直接在 printf()、strcpy() 等中使用回傳值...
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/462592.html
