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!
We pay for user submitted tutorials and articles that we publish. Anyone can send in a contribution
Learn More
James Curran Said on Jan 12, 2009 :
It’s interesting to note that shortly after that technique was devised, a somewhat anonomoused version:
template
int func(T(&)[N]){return N;}
was passed around members of the C++ Standardization Committee, and it usually took quite a while for the recipient to figure out what it did.
Steve Vinoski Said on Jan 13, 2009 :
For an array named “arr” just do this:
sizeof(arr)/sizeof(*arr)
No need for templates here, no need to specify the item type in the divisor, and it works perfectly in both C++ and C.
Troy Said on Jan 13, 2009 :
Wow, neat trick, any chance you can explain how it works exactly?
James Curran Said on Jan 14, 2009 :
@troy:
It’s fairly straight forward. The compiler uses parameter resolution to create a version of the function that matches that parameter passed to it, so :
int arr[17];
int arrSize = GetArrLength(arr);
is essentially
int arr[17];
int arrSize = GetArrLength(arr);
which creates this function:
int GetArrLength(int(&)[17]){return 17;}
James Curran Said on Jan 14, 2009 :
The comment editor mangled that:
“that is essentially:
int arr[17];
int arrSize = GetArrLength<int, 17>(arr);
OJ Said on Jan 27, 2009 :
Bear in mind that things aren’t so simple when dealing with dynamically allocated arrays.
Kristof Said on Feb 19, 2009 :
Don’t put it in a seperate function, because you will get this:
int array[20];
int GetArrayLength(int array[])
{
return sizeof array / sizeof array[0];
}
Because you only pass the first element of the array to the function, so this will always return 1