C and C ++ do not provide functions that directly obtain the length of an array. For character arrays that store strings, A strlen function is provided to obtain the length, so how can we get their lengths for arrays of other types? One of the methods is to use sizeof (array)/sizeof (array [0]). In C language, it is used to define it as a macro, for example, # define get_array_len (array, Len) {Len = (sizeof (array)/sizeof (array [0]);}. In C ++, you can use the template technology to define a function, for example:
Template <class T>
Int getarraylen (T & array)
{
Return (sizeof (array)/sizeof (array [0]);
}
In this way, you can use this macro or this function to obtain the length of the array for different types of data groups. The following are two demo programs, one in C and one in C ++:
P.s: If the array is a character array that stores strings, the obtained length must be reduced by one, that is, for macro definition: # define get_array_len (array, Len) {Len = (sizeof (array)/sizeof (array [0])-1) ;}, for Function Definition:
Template <class T>
Int getarraylen (T & array)
{
Return (sizeof (array)/sizeof (array [0])-1 );
}
The reason is that there is a '\ 0' character at the end of the character array storing the string. You need to remove it.
[C Language]
# Include <stdio. h>
# Include <stdlib. h>
# Define get_array_len (array, Len) {Len = (sizeof (array)/sizeof (array [0]);}
// Define a macro with parameters and store the array length in the variable Len
Int main ()
{
Char A [] = {'1', '2', '3', '4 '};
Int Len;
Get_array_len (A, Len)
// Call a predefined macro to get the length of array A and store it in the variable Len
Printf ("% d \ n", Len );
System ("pause ");
Return 0;
}
[C ++]
# Include <iostream>
Using namespace STD;
Template <class T>
Int getarraylen (T & array)
{// Use a template to define a function getarraylen, which returns the length of the array.
Return (sizeof (array)/sizeof (array [0]);
}
Int main ()
{
Char A [] = {'1', '2', '3 '};
Cout <getarraylen (a) <Endl;
Return 0;
}
In addition, if an array is passed as a parameter in the C ++ function, the array will be degraded into a pointer, therefore, the length of the array is unknown (the array here refers to static instead of new ).