gpt4 book ai didi

c - 这个结构的大小是多少?

转载 作者:太空宇宙 更新时间:2023-11-04 05:53:20 32 4
gpt4 key购买 nike

 typedef struct {
char valid;
char tag;
char block[4];
} line;

我相信它是 6,因为 block[] 是 4,每个 char 是 1 个字节。这是在 x86 机器上。 validtag 之间是否有偏移?应该是 8 吗?

最佳答案

如果您想要结构的大小,请使用 sizeof 运算符。

例如

size_t struct_size = sizeof(line);

它以字节为单位返回结构的大小。注意 sizeof(char) == 1 总是,所以技术上字节并不总是意味着 8 位。

来自 C:TCN, "Page 348" at the bottom of the page :-

It is in theory possible for a machine to have char be larger than 8 bits, though it's not very common for hosted environments (basically, desktop computers and the like -- the only environments required to even have the functions to begin with).

On such a machine, contrary to many people's expectations, sizeof(char) is still 1; what changes is the value CHAR_BIT. The relevance of this is that, on such a machine, it is possible for int to still have its required range, but to be the same size as a char.

Thus, on such a machine, there might exist at least one value of unsigned char such that, converted to int, it was a negative value, and compared equal to EOF. However, to the best of my knowledge, all such systems that have provided the getchar() function and related functions have ensured that, in fact, the EOF value is distinct from any value which can actually be read from a file. For instance, char could be a 32-bit type, but you would still only see values 0-255 when reading "characters" from a file.

来自 WG14 n1256 - 第 6.5.3.4 节:

The sizeof operator yields the size (in bytes) of its operand ... When applied to an operand that has type , unsigned char, or signed char, (or a qualified version thereof) the result is 1.

关于c - 这个结构的大小是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33818728/

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