gpt4 book ai didi

c - 无符号整数的大小为 8

转载 作者:太空宇宙 更新时间:2023-11-04 07:55:22 27 4
gpt4 key购买 nike

<分区>

我很困惑为什么 clientIf 即使声明为 uint32(unsigned int - 大小 4 字节),也会占用 8 个字节。我已明确打印 sizeof(uint32) 并显示 4 个字节。

谁能提出一些见解。

我在一台小端机器 x86 上运行这段代码。

#include <stdio.h>
#include <string.h>

/* network defines */
typedef char uint8;
typedef short uint16;
typedef unsigned int uint32;
typedef uint32 ipv4Addr;

/*********************** V6 IP ADDRESS **********************************/
typedef struct _v6IpAddr
{
union _Bytes
{
uint8 rbyte[16];
uint16 doublebyte[8];
uint32 wordbyte[4];
long long dwordbyte[2];
}unionv6;
#define dbyte unionv6.doublebyte
#define wbyte unionv6.wordbyte
#define dwbyte unionv6.dwordbyte
#define xbyte unionv6.rbyte
}v6IpAddr;

typedef struct _v6IpAddr uint128;

typedef union _comIpAddr
{
ipv4Addr v4Ip;
v6IpAddr v6Ip;
}comIpAddr;

typedef struct abc
{
/*|*/uint32 clientIf; /*|*/
/*|*/comIpAddr clientIp; /*|*/
/*|*/uint8 mac[6]; /*|*/
/*|*/uint16 zero; /*|*/
}ABC;

void print_bytes(const void *object, size_t size)
{
// This is for C++; in C just drop the static_cast<>() and assign.
const unsigned char * const bytes = object;
size_t i;

printf("[ ");
for(i = 0; i < size; i++)
{
printf("%02x ", bytes[i]);
}
printf("]\n");
}

int main()
{
ABC test;
memset(&test,0,sizeof test);
printf("sizeof test = %u\n", sizeof test);
printf("%d-%d-%d\n", sizeof(uint8), sizeof(uint16), sizeof(uint32));

print_bytes(&test, sizeof test);
test.clientIf = 10;
test.clientIp.v4Ip = 0xAABBCCDD;
print_bytes(&test, sizeof test);
printf("%p-%p-%p\n", &(test.clientIf), &(test.clientIp), &(test.clientIp.v4Ip));
return 0;
}

$./a.out

测试大小 = 32

1-2-4

[00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ]

[ 0a 00 00 00 00 00 00 00 dd cc bb aa 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ]

0x7fff113b0780-0x7fff113b0788-0x7fff113b0788$

编辑:

为什么编译器会在 clientIf 之后添加填充,因为它已经是 4 字节的倍数?

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