计算数组长度

int array[] = { 23, 34, 12, 17, 204, 99, 16};
#define TOTAL_ELEMENTS (sizeof(array)/sizeof(array[0]))
  • sizeof() 返回值类型为无符号数
  • 使用 array[0] 可以在不修改宏定义语句的情况下改变数组的基本类型,比如由 int 改成 char

PS.
另一种宏定义方法是:#define TOTAL_ELEMENTS (sizeof(array)/sizeof(int))

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google+ photo

You are commenting using your Google+ account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.