关于C++中的strlen与sizeof,很多时候,如果不注意还是会弄混的,今天特意总结一下
sizeof求占用内存的大小
strlen求的字符串的长度
#include<iostream>
using namespace std;
int main(){
char man[12]={"hello world"};
cout<<"strlen(man)"<<strlen(man)<<endl; //11
cout<<"sizeof(man)"<<sizeof(man)<<endl; //12
man[5]='\0';
cout<<"strlen(man)"<<strlen(man)<<endl;//5
cout<<"sizeof(man)"<<sizeof(man)<<endl;//12
}
关于字符串hello world 最后面还有一个结束字符'\0',故其长度为11
占用内存:每个char占用1个字节,故共占用12个字节
当man[5]='\0';
即man[12]={"hello\0world"}
再用使用strlen求长度的时候,遇到\0则停止,故长度为5
其占用内存还是12没有发生变化