有没有比这个 C 代码更短的方法来查找数组的长度?
static int a[] = {1, 5, 645, 43, 4, 65, 5408, 4, 7, 90, 23, 11};
int len=sizeof(a)/sizeof(int);
ANSI 99 有捷径吗?
static int a[] = {1, 5, 645, 43, 4, 65, 5408, 4, 7, 90, 23, 11};
int len=sizeof(a)/sizeof(int);
Is there a shortcut, with ANSI 99?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为没有捷径,但你可以使用宏:
I think that there isn't a shortcut, but you cat use macro:
是的,短一个字符:
编辑:@pmg 建议使用更短的版本:
您还可以使用更少的字符作为标识符
len
。:)
Yes, one character shorter:
edit: There's an even shorter version suggested by @pmg:
You could also use fewer characters for the identifier
len
.:)
如果您想要数组中的元素数量,
或者
尽可能短。请记住,除非
arr
是 VLA,否则这些将在编译时计算。另请记住,只有当
arr
是数组表达式而不是指针时,这才有效。如果你这样做,你将不会得到你期望的答案,因为在这种情况下,
arr
是一个指针表达式,而不是一个数组(请参阅在线C 语言标准,§ 6.3.2.1 ¶ 3和§ 6.5.7.3 ¶ 7)。If you want the number of elements in the array,
or
are about as short as it gets. Just remember that unless
arr
is a VLA, these will be computed at compile time.Also remember that this only works if
arr
is an array expression, not a pointer. If you do something likeyou won't get the answer you expect, because in this context
arr
is a pointer expression, not an array (refer to the online C language standard, § 6.3.2.1 ¶ 3 and § 6.5.7.3 ¶ 7).