简体   繁体   English

数组元素的大小 C

[英]Size of element of array C

Consider the line <type> array[SIZE_OF_ARRAY];考虑行<type> array[SIZE_OF_ARRAY]; . . Later I need to use the size of an element of this array (ie for a fwrite ).稍后我需要使用这个数组的一个元素的大小(即对于fwrite )。 However I might change the <type> in future, so can't have a fixed size.但是我将来可能会更改<type> ,所以不能有固定的大小。 The solution I found was to use sizeof(array[0]) .我找到的解决方案是使用sizeof(array[0]) While it works for my case, it doesn't feel very pretty, and it would run into problems if the array could be empty.虽然它适用于我的情况,但感觉不是很漂亮,如果数组可能为空,它会遇到问题。 Is there a better alternative?有更好的选择吗?

if the array could be empty.如果数组可以为空。 Is there a better alternative?有更好的选择吗?

Array may not be empty.数组不能为空。 It can be uninitialized.它可以未初始化。 Nevertheless this expression不过这个表达

sizeof(array[0])

is in any case valid because the operand is unevaluated expression in the sense that there is no access to the memory (though the expression itself can be evaluated at run time if array[0] is in turn a variable length array).在任何情况下都是有效的,因为从无法访问 memory 的意义上说,操作数是未计算的表达式(尽管如果array[0]又是可变长度数组,则表达式本身可以在运行时进行计算)。

An alternative expression can look like另一种表达方式可能看起来像

sizeof( *array )

You may use either expression with the same effect.您可以使用具有相同效果的任一表达式。

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

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