C++获取数组长度

1、获取字符数组长度

char a[]="abcdef";

int length1=sizeof(a)/sizeof(a[0]);
cout<<"a"<<length1<<endl;

length1为7.

cout<<"a"<<strlen(a)<<endl;

输出6

注:string不能用strlen函数

2、获取字符串string长度

#include <string>
#include <iostream>
using namespace std;
int main()
{
string str = "abcdef";
cout << str.length() << endl;
cout << str.size() << endl;
return 0;
}

输出皆为6

3、获取int数组长度

int marks[5] = {40, 90, 73, 81, 35};
int length1=sizeof(marks)/4;
cout<<"a"<<length1<<endl;

输出为5,实际长度

获取二维数组长度:

int marks[2][3]={1,2,3,4,5,6};
int length1=sizeof(marks[0])/4;
cout<<"a"<<length1<<endl;
int length2=sizeof(marks)/4;
cout<<"a"<<length2<<endl;

输出3,和6

 

posted on 2017-06-08 23:04  那年月光  阅读(1790)  评论(0编辑  收藏  举报