Although a char is composed of 1 byte on all compilers I know, I was under the impression that C doesn't guarantee the length of a char, it only guarantees that char < short < long. Therefore I assumed that sizeof measures its result in chars in order to abstract from the platform it's running on. To make it more general, I thought that size_t is defined in terms of char.

But now, as far as I can see searching on google, it appears that sizeof does return its result in bytes.

Was I completely wrong in my assumption or is there more to it than that?

有帮助吗?

解决方案 3

char is the C data type that represents a byte; they're conceptually the same.

If you're asking whether the result is always in octet's (8-bit values), the answer is no; it's in bytes (chars), and if a byte happens to have a different number of bits then the result will be in terms of multiples of that many bits.

其他提示

The unit used by sizeof is the char. One of the axioms of the language is that sizeof(char) == 1.

Hence, for systems where char is larger than 8 bits, sizeof does not measure in 8 bit units.

The units for sizeof is chars.

However, C defines a byte to be the size of a char, and not the more common usage where a byte equals 8 bits.

If you want to know how many bits a char is, use the CHAR_BIT constant in <limits.h>

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top