Click here to Skip to main content
15,888,803 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello everyone,
How can i be able to make a function be assigned with a generic type parameter in C
for example in order to get the length of an array i use the following,
C++
int n;
n = (sizeof(array)/ sizeof(array[0]));

i find this statement useful and i want to put it in a generic function, but an array can be of any type, how to make the function receive any 1D array of any type.

Thanks in advance,
z3ngew
Posted

Assuming that by array, you are talking about traditionnal C style array like this one:
C++
int anArray[25];

If you don't need compile-time value, then the following function will be able to evaluate the number of items in any array.
C++
template <typename T, int n> int len(T(&array)[n])
{
    return (sizeof(array)/ sizeof(array[0]));
}

You can then get the length like that:
C++
int n = len(anArray);

Since that code will only compile for arrays and not pointers, the template is safer to uses as it would not compile with pointers (or the equivalent int not_really_an_array[]).

Also, in the Template function, one could simply write return n; but I have copied the original code (including all superfluous parenthesis) to make it clear that I do same thing.
 
Share this answer
 
v4
Comments
Sergey Alexandrovich Kryukov 29-Aug-13 0:29am    
Quite convincing (especially the last sentence :-), a 5.
—SA
nv3 29-Aug-13 1:56am    
My 5.
your solution is perfect but ansi c does not support
C++
template
so here is the solution in c

C++
#define ARRAY_SIZE(x)  (sizeof(x) / sizeof(x[0]))


you can pass any type of array in this function,
Thanks for your effort everyone,

z3ngew
 
Share this answer
 
Comments
Philippe Mori 1-Sep-13 8:38am    
Well, although you mention C in the question, it was also tagged as C++ and you were taking about generic functions which make us think you want a template function.

With the C macro, you just have to be careful to use it only when it can be used (array with compile-time known size).

In pratice, it might offten be preferable to declare a constant and used that constant instead. const int n =5; int x[n]; particulary if you need to declare multiple arrays of that same size.
z3ngew 1-Sep-13 12:28pm    
I'm sry for the confusion, and about using a constant, it really solve it perfectly but sometimes you just need to return the length of the array without declaring it previously.

Thanks for your effort,

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900