简体   繁体   English

一行C代码的逻辑

[英]logic of a line of C code

Could you please tell me the logic of using sizeof data / sizeof *data in this code line 17? 您能否告诉我在此代码行17中使用sizeof data / sizeof *data的逻辑?

...
unsigned char data[16];
...
size = fread(data, sizeof *data, sizeof data / sizeof *data, file);
...

Thanks 谢谢

That's a common C idiom for "number of elements in an array". 这是“数组中元素数量”的常见C习惯用法。

Since an array decays to a pointer at the slightest provocation, *data is the first element of the array, and therefore it's dividing the total size of the array by the size of its first element, giving a count of elements. 由于数组在丝毫挑衅下会衰减为指针 ,因此*data是数组的第一个元素,因此它将数组的总大小除以其第一个元素的大小,得到一个元素数。

There are any number of possible objections to this technique, whether on style grounds, the fact that it only works on variables declared as arrays (not those passed as pointer to the first element -- it relies on the decay-to-pointer not having happened yet), or possible breakage scenarios in C++ code; 对该技术有很多可能的反对意见,无论是基于样式,还是它仅适用于声明为数组的变量(不适用于作为指向第一个元素的指针的变量),它都依赖于无指针衰减尚未发生),或C ++代码中可能发生的破坏情况; that said, it remains common in older C code. 也就是说,它在较旧的C代码中仍然很常见。

It divides the total size of the array by the size of the type of each element. 它将数组的总大小除以每个元素类型的大小。 It returns the number of elements in the array 它返回数组中的元素数

It gives you the number of elements in the array. 它为您提供了数组中元素的数量。 Because it's a compile-time value and not a run-time value, it doesn't actually evaluate anything inside the sizeof() , which is nice because it works even if any pointers are null or out of bounds. 因为它是一个编译时值,而不是运行时值,所以它实际上不评估sizeof()内的任何内容,这很好,因为即使任何指针为null或超出范围,它也可以工作。

(Fun facts: i the Windows C runtime, there's already a _countof() macro that does exactly that, and in the Windows SDK, there's the ARRAYSIZE() macro that also does the same thing.) (有趣的事实:在Windows C运行时中,已经有一个_countof()宏可以完全做到这一点,而在Windows SDK中,有ARRAYSIZE()宏也可以完成相同的工作。)

它只是在计算数组中元素的数量-即,整个数组的大小除以数组中第一个元素的大小即可得出元素的数量(数组中的所有元素都具有相同的大小)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM