问题
The C standard mandates sizeof(char)
to be 1, no matter how many bits it actually takes.
Are other data-types measured in terms of bytes or chars in case these are not the same?
Basically, assuming CHAR_BIT
is 16, would sizeof(int16_t)
be equal to 1 or 2?
回答1:
Basically, assuming CHAR_BIT is 16, would sizeof(int16_t) be equal to 1 or 2
Size of objects (as yielded by sizeof
operator) is measured in bytes and a byte in C has CHAR_BIT
bits.
(C99, 6.2.6.1p4) "Values stored in non-bit-field objects of any other object type consist of n x CHAR_BIT bits, where n is the size of an object of that type, in bytes."
int16_t
type if present has a width of exactly 16-bit and no padding. This means if CHAR_BIT == 16
, then sizeof (int16_t) == 1
回答2:
If CHAR_BIT
is 16 and int16_t
exists, then sizeof(int16_t) == 1
. The int8_t
type would not exist, because everything in C must be measurable in bytes (and on this system, each byte would be 16 bits... this is why the term "octet" is more precise than "byte").
There are DSP systems and old supercomputers (earlier Cray systems) where short
, int
, long
all have the same size, say 64 bits.
回答3:
There are no limitations on the sizes of types; they only have to be able to represent a minimum range of values. It's perfectly legitimate, say, for a platform to have all its fundamental types be 64 bit wide and sizeof
of each of them would be 1
.
Since arrays require contiguous storage, and adjacent array elements must be accessible without inventing writes, a platform may have to choose "large char
s" to accommodate for the smallest unit of memory it can address independently.
来源:https://stackoverflow.com/questions/21080114/if-char-bit-8-what-is-the-size-of-other-types