C++获取数组的长度(用模板可以实现)
#include<iostream>
using namespace std;
int getArrLen1(int *&a){//error
return sizeof(a)/sizeof(a[0]);
}
int getArrLen2(int *a){
return sizeof(a)/sizeof(a[0]);
}
template<typename T>
int getArrayLength1(T a){
return sizeof(a)/sizeof(a[0]);
}
/**
正确的获取数组长度的函数(虽然是模板)
*/
template<typename T>
int getArrayLength2(T &a){
return sizeof(a)/sizeof(a[0]);
}
int main(){
int *p = new int[200];
int size = *(p-4);
cout << size << endl;
size = *(p-3);
cout << size << endl;
size = *(p-2);
cout << size << endl;
size = *(p-1);
cout << size << endl;
int a[100];
cout << "a address:" << a << endl;
cout << "&a address:" << &a << endl;
/*
C:UsersjackzDesktopcodescpp>g++ getArrayLength.cpp
getArrayLength.cpp: In function "int main()":
getArrayLength.cpp:39:22: error: invalid initialization of non-const reference o
f type "int*&" from an rvalue of type "int*"
cout << getArrLen1(a) << endl;
^
getArrayLength.cpp:4:5: note: initializing argument 1 of "int getArrLen1(int*&
)"
int getArrLen1(int *&a){
^
*/
//cout << getArrLen1(a) << endl;//error
//cout << "&&a address:" << &&a << endl;//error
cout << getArrLen2(a) << endl;
cout << getArrayLength1(a) << endl;//1
cout << getArrayLength2(a) << endl;//100
return 0;
}
C:UsersjackzDesktopcodescpp>g++ getArrayLength.cpp C:UsersjackzDesktopcodescpp>a 0 0 1633043277 134352027 a address:0x28fd78 &a address:0x28fd78 1 1 100
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: React遍历数组
- 下一篇: 【vuejs】vue数组操作
