浙江省高等学校教师教育理论培训

微信搜索“毛凌志岗前心得”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

http://www.dev102.com/2009/01/12/c-tip-how-to-get-array-length/

C++ Tip: How To Get Array Length | Dev102.com

Getting an array length in C# is a trivial task. All we need to so is call the Length property of the Array Class:

int[] arr = new int[17];
int arrLength = arr.Length;

 

Getting an array length in C++ might be less trivial:

int arr[17];
int arrSize = sizeof(arr) / sizeof(int);

Notice that sizeof(arr) returns the array size in bytes, not its length, so we must remember to divide its result with the size of the array item type (sizeof(int) in the example above).

I want to show you this nice C++ macro which helps us getting an array length in another and better way:

template<typename T, int size>
int GetArrLength(T(&)[size]){return size;}

This is how to use it:

template<typename T, int size>
int GetArrLength(T(&)[size]){return size;}

void main()
{
    int arr[17];
    int arrSize = GetArrLength(arr);
}

aarSize will be equal to 17. Enjoy!

posted on 2013-01-06 11:17  lexus  阅读(331)  评论(0编辑  收藏  举报