C, C + + does not provide direct access to the array length of the function, for the character array holding the string provides a strlen function to get the length, then for other types of arrays how to get their length? One method is to use sizeof (array)/sizeof (array[0]), which is used in C to define it as a macro, such as # define Get_array_len (Array,len) {LEN = (sizeof ( Array)/sizeof (array[0]);} 。 In C + +, you can use template technology to define a function, such as:
Template <class t>
int Getarraylen (t& array)
{
Return (sizeof (array)/sizeof (array[0));
}
This allows you to use this macro or this function to get the length of the array for different types of arrays. Here are two demo programs, a C language, and a C + +:
P.S: If the array is an array of characters that store strings, then the length to be calculated also needs to be reduced by one, that is, the definition of macro: #define Get_array_len (array,len) {LEN = (sizeof (ARRAY)/sizeof (array[0])-1); }, for function definitions:
Template <class t>
int Getarraylen (t& array)
{
Return (sizeof (array)/sizeof (array[0])-1);
}
The reason is that the character array that stores the string has a ' + ' character at the end, and it needs to be removed.
"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 to store the length of the array 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)
{//using a template to define a function Getarraylen, the function returns the length of an array of arrays
Return (sizeof (array)/sizeof (array[0));
}
int main ()
{
Char a[] = {' 1 ', ' 2 ', ' 3 '};
cout << Getarraylen (a) << Endl;
return 0;
}
Another: in C + + functions, if an array is passed in as a parameter, then the array will degenerate into a pointer, so it is not known the length of the array (the array here refers to static rather than new).
This article from Csdn Blog, reproduced please indicate the source: http://blog.csdn.net/bopzhou/archive/2010/12/08/6063163.aspx
How do I get the length of an array in C + +?