Click here to Skip to main content
14,327,765 members
Rate this:
Please Sign up or sign in to 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,
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
Rate this:
Please Sign up or sign in to vote.

Solution 2

Assuming that by array, you are talking about traditionnal C style array like this one:
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.
template <typename T, int n> int len(T(&array)[n])
{
    return (sizeof(array)/ sizeof(array[0]));
}

You can then get the length like that:
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.
   
v4
Comments
   
Quite convincing (especially the last sentence :-), a 5.
—SA
nv3 29-Aug-13 1:56am
   
My 5.
Rate this:
Please Sign up or sign in to vote.

Solution 3

your solution is perfect but ansi c does not support
template
so here is the solution in 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
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100