As anyone who has learned C + + is aware that there is no function to get the length of an array directly in C + +, for a character array that holds a string provides a strlen function to get its length, how do you get their length for other types of arrays?
One way to do this is to use sizeof (array)/sizeof (ARRAY[0) to define it as a macro when used in C, 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));
}
So for some simple arrays you can use this macro or this function to get the length of the array.
Here are two demo programs, a C language, a C + +:
Note: if the array is a character array that stores strings, that is, an array of characters that are initialized with a literal string enclosed in double quotes
For example:
Or
The length that is evaluated is the length of the character array, rather than the length of the corresponding string, requiring the length of the string to be reduced by one. The reason is that the character array at the end of the string has a '. ' character, which needs to be removed.
For the following example:
Char a[]= "ABCDEFG";
sizeof (a)/sizeof (a[0]) = 8;
If the string length is required, it should be reduced by 1.
But for:
Char a[]={' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' G '};
sizeof (a)/sizeof (a[0]) =7
C language examples are as follows:
#include <stdio.h>
#include <stdlib.h>
#define Get_array_len (array,len) {LEN = (sizeof (ARRAY)/ sizeof (array[0]));
Defines a macro with parameters that store the length of the array in variable len
int main ()
{
char a[] = {' 1 ', ' 2 ', ' 3 ', ' 4 '};
int Len;
Get_array_len (A,len)
//Invokes a predefined macro, obtains the length of array A and stores it in variable LEN
("%d\n", Len);
System ("pause");
return 0;
}
The output is: 4
C + + examples are as follows:
#include <iostream>
using namespace std;
Template <class t>
int getarraylen (t& array)//using a template to define a function Getarraylen, which returns the length of array arrays
{
Return (sizeof (array)/sizeof (array[0]));
}
int main ()
{
char a[] = {' 1 ', ' 2 ', ' 3 '};
cout << Getarraylen (a) << Endl;
return 0;
}
The output is: 3