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

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!

你可能感兴趣的:(length)