发布日期:2018-03-26
如何使用C++得到数组的长度?+ 查看更多
如何使用C++得到数组的长度?
+ 查看更多
发布日期:2018-02-26 15:53
分类:CPlusPlus
浏览次数:124
有可以返回数组的长度同时可以检测是的否到达数组的末尾的方法吗?
回答:
如果你的意思是C语言系列的数组,那么你可以这样做:
int a [7]; std :: cout <<“Length of array =”<<(sizeof(a)/ sizeof(* a))<< std :: endl;
虽然这种方法不使用指针,它和以下面方法一样:
int * p = new int [7]; std :: cout <<“Length of array =”<<(sizeof(p)/ sizeof(* p))<< std :: endl;
或者:
void func(int * p) { std :: cout <<“Length of array =”<<(sizeof(p)/ sizeof(* p))<< std :: endl; }} int a [7]; func(a);
在C ++中,如果你想要这种方法,那么你应该使用一个容器类; 例如std :: vector。