这两个的区别,记了又忘,索性通过代码记忆
#include<iostream>
using namespacestd;
int main()
{
//字符串常量作为字符指针
char* a = "hello";
cout<<"length about sizeof:"<<sizeof(a)<<" "<<"lengthabout strlen:"<<strlen(a)<<endl; //(sizeof显示的是指针的大小,为4,strlen则只能从字符起始,找到’\0’为止,为5)
//字符数组
char b[] = {'h','e','l','l','o'};
cout<<"length about sizeof:"<<sizeof(b)<<" "<<"lengthabout strlen:"<<strlen(b)<<endl;//(sizeof为5,为数组元素个数,strlen为31,由于字符数组没有指定’\0’,strlen会一直向后找到’\0’元素为止)
//以字符串常量初始化字符数组
char c[] = "hello";
cout<<"length about sizeof:"<<sizeof(c)<<" "<<"lengthabout strlen:"<<strlen(c)<<endl; //(sizeof为6,字符常量默认加了’\0’.strlen为5, strlen找到’\0’元素为止,但不将最后的’\0’元素记入计数)
//定义好长度的字符数组
char d[10]= "hello";
cout<<"length about sizeof:"<<sizeof(d)<<" "<<"lengthabout strlen:"<<strlen(d)<<endl; //(sizeof为10,以数组设定长度为准.strlen为5, strlen找到’\0’元素为止,但不将最后的’\0’元素记入计数)
char e[] = {'h','e','\0','l','l','o'};
cout<<"length about sizeof:"<<sizeof(e)<<" "<<"lengthabout strlen:"<<strlen(e)<<endl; //(sizeof为6,为数组元素个数.strlen为2, strlen找到’\0’元素为止,但不将最后的’\0’元素记入计数)
getchar();
}