包括在struct中更改sizeof in_addr

mwa*_*ing 11 c

好的,我有一个包含struct in_addr元素的结构.这应该使struct addrlist_t至少有12个字节(8 + 4).平台是amd64.

#include <netinet/in.h> // struct in_addr
#include <stdio.h> // printf()
#include <netdb.h> // toggles size of struct addrlist_t

struct addrlist_t {
    struct addrlist_t *next;
    struct in_addr h_addr;
};

int main(int argc, char *argv[]) {
    printf("%zu + %zu = %zu\n",
        sizeof (struct addrlist_t *), sizeof (struct in_addr), 
        sizeof (struct addrlist_t)
    );
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是完全出乎意料的输出:

$cc main.c -o main -Wall -Wwrite-strings -pedantic -std=gnu99 -Wall -Werror
$./main
8 + 4 = 8
Run Code Online (Sandbox Code Playgroud)

这似乎毫无意义.组合尺寸应至少为12,而不是更小!

但是现在,当#include &lt;netdb.h&gt;删除时,会出现预期的输出:

$./main
8 + 4 = 16
Run Code Online (Sandbox Code Playgroud)

-std=gnu99被替换时会发生同样的事情-std=c99.

有人可以解释这种行为吗?

为了完整性:

$file main
main: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, BuildID[sha1]=709ab89d012d8b5a6ae7423fd80ce643288cba95, not stripped
Run Code Online (Sandbox Code Playgroud)

编辑:格式/单词

nos*_*nos 15

这是因为你有一个不幸的名字struct in_addr h_addr.

<netdb.h> 在glibc中包含:

# define    h_addr  h_addr_list[0] /* Address, for backward compatibility.*/                       
Run Code Online (Sandbox Code Playgroud)

运行gcc -E main.c来看看你的代码在预处理之后的样子,你的struct addrlist_t基本上变成了这样:

struct addrlist_t {
    struct addrlist_t *next;
    struct in_addr h_addr_list[0];
};
Run Code Online (Sandbox Code Playgroud)

这与你的意图完全不同.