简体   繁体   中英

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?

...
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".

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.

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; that said, it remains common in older C code.

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.

(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.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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