How to get the length of an array in C++

Use the sizeof keyword to get the length of an array without using other containers:

template <class T>
int length(T& a) {
	return sizeof(a) / sizeof(a[0]);
}

Note that the above method has been found so far , and length(arr) can be used directly when using it, where arr can be of any type.

All of the following will go wrong :

//error one
template <class T>
int length(int& a) {
	return sizeof(a) / sizeof(a[0]);
}
//error two
int length(int& a) {
	return sizeof(a) / sizeof(a[0]);
}
//error three
int length(int *a) {
	return sizeof(a) / sizeof(a[0]);
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325911811&siteId=291194637