gpt4 book ai didi

c - 在结构中包含更改 sizeof in_addr

转载 作者:太空狗 更新时间:2023-10-29 16:43:58 25 4
gpt4 key购买 nike

好的,我有一个包含 struct in_addr 元素的结构。这应该使结构 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;
}

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

$cc main.c -o main -Wall -Wwrite-strings -pedantic -std=gnu99 -Wall -Werror
$./main
8 + 4 = 8

这似乎没有意义。组合大小应至少为 12,不能更小!

但是现在,当 #include <netdb.h> 被移除时,预期的输出出现:

$./main
8 + 4 = 16

-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

编辑:格式/文字

最佳答案

这是因为您为 struct in_addr h_addr 取了一个不幸的名字成员(member)。

<netdb.h>在 glibc 中包含这个:

# define    h_addr  h_addr_list[0] /* Address, for backward compatibility.*/                       

运行 gcc -E main.c 以查看您的代码在预处理后的外观,你的 struct addrlist_t 基本上变成了这样:

struct addrlist_t {
struct addrlist_t *next;
struct in_addr h_addr_list[0];
};

这与您的预期完全不同。

关于c - 在结构中包含更改 sizeof in_addr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28043087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com