Geeks With Blogs
Robert Bernstein's Blog Adventures in Windows, .NET, and C++

I'm dividing my time between the .NET world and developing in C++ again, so I'm going to be posting some handy snippets here.

Rather than using:

sizeof(array) / sizeof(element)

to determine the size of an array, we can use a template to accomplish this.

 

//
// A handy two-line array_size() template function
//
#include <cstdlib>
#include <iostream>
using namespace std;


// Uses template type induction to
// discover the size of an array
// so that you don't have to use sizeof(array)/sizeof(element)
template<typename T, int size>
int array_size(T (&)[size]) { return size; };


int main(){

int my_array[] = { 1, 2, 3, 4, 5 };// implicit size

cout << "array size is : " << array_size(my_array) <<  endl;

system("pause");
}

 

This code was borrowed from http://www.velocityreviews.com/forums/t283787-how-to-know-the-buffer-size-and-increase-buffer-size-in-c.html.  Thanks for the great code sample!

Rob

Posted on Wednesday, June 30, 2010 10:35 AM C++ | Back to top


Comments on this post: C++ Array Size Function

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Rob | Powered by: GeeksWithBlogs.net