一段代碼幫助記憶,如下:
CString str1="abcdef";
char str2[ ]={'a','b','c','d','e','f','\0'};
char str3[ ]="abcdef";
int len1=strlen(str1);
int size1=sizeof(str1);
int len2=strlen(str2);
int size2=sizeof(str2);
int len3=strlen(str3);
int size3=sizeof(str3);
CString str;
str.Format("%d %d %d %d %d %d ",len1,size1,len2,size2,len3,size3);
AfxMessageBox(str);
結果是:6 4 6 7 6 7
注:如果str2數組裏面沒加\0,那麼strlen將會不知道在哪裏結束,得到的值也是一個隨機值。sizeof得到的是所佔內存的字節大小,而strlen得到的是字符個數。sizeof比strlen大1,說明字符串在內存裏面在最後自動加上了\0 。第二個數字是4,說明sizeof得到的是CString對象所佔內存大小。