C++获取数组的长度(用模板可以实现)

来源:互联网 发布:梦里花落知多少意思 编辑:程序博客网 时间:2024/06/10 03:56
#include<iostream>using namespace  std;int getArrLen1(int *&a){//errorreturn 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:\Users\jackz\Desktop\codes\cpp>g++ getArrayLength.cppgetArrayLength.cpp: In function 'int main()':getArrayLength.cpp:39:22: error: invalid initialization of non-const reference of 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;//errorcout << getArrLen2(a) << endl;cout << getArrayLength1(a) << endl;//1cout << getArrayLength2(a) << endl;//100return 0;}

C:\Users\jackz\Desktop\codes\cpp>g++ getArrayLength.cppC:\Users\jackz\Desktop\codes\cpp>a001633043277134352027a address:0x28fd78&a address:0x28fd7811100

0 0
原创粉丝点击