生活随笔
收集整理的這篇文章主要介紹了
sizeof和strlen()区别
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2017 -
12 -
19 創(chuàng)建人:Ruo_Xiao
郵箱:xclsoftware
@163 .com
2018 -
01 -
16 修改人:Ruo_Xiao
增加strlen的頭文件的說明。
#include "stdafx.h"
#include "iostream"
using namespace std ;
int add(
int i,
int t)
{
return (i+t);
}
int _tmain(
int argc, _TCHAR* argv[])
{
int iData1[
5 ];
double dData2[
7 ];
int *pData =
new int [
3 ];
char *p1 =
"12345" ;
char *p2 =
new char [
3 ];
char p3[] =
"Hello World" ;p2[
0 ] =
'1' ;p2[
1 ] =
'2' ;p2[
2 ] =
'3' ;p2[
3 ] =
'3' ;p2[
4 ] =
'4' ;
memset (iData1,
0 ,
sizeof (
int )*
5 );
memset (dData2,
0 ,
sizeof (
double )*
7 );
cout <<
"sizeof(iData1) = " <<
sizeof (iData1)<<endl;
cout <<
"sizeof(dData2) = " <<
sizeof (dData2)<<endl;
cout <<
"sizeof(pData2) = " <<
sizeof (pData)<<endl;
cout <<
"sizeof(double) = " <<
sizeof (
double )<<endl<<endl;
cout <<
"sizeof(p1) = " <<
sizeof (p1)<<endl;
cout <<
"sizeof(*p1) = " <<
sizeof (*p1)<<endl<<endl;
cout <<
"sizeof(p3) = " <<
sizeof (p3)<<endl;
cout <<
"strlen(p3) = " <<
strlen (p3)<<endl<<endl;
cout <<
"strlen(p1) = " <<
strlen (p1)<<endl;
cout <<
"strlen(p2) = " <<
strlen (p2)<<endl;
cin .get();
return 0 ;
}
運行結(jié)果如下:
一、sizeof
“sizeof”是操作符。 返回值的類型是size_t,它在頭文件中定義如下: typedef unsigned int size_t; 返回值意義是保證能容納實現(xiàn)所建立的最大對象的字節(jié)大小。 參數(shù)可以是數(shù)組、指針、類型、對象等。 編譯時執(zhí)行。 由上述例子的運行結(jié)果可知: (1)當(dāng)形參是一個結(jié)構(gòu)類型或變量時, sizeof 返回實際的大小。 (2)當(dāng)形參是一個靜態(tài)地址空間時, sizeof 歸還全部數(shù)組的所占的字節(jié)數(shù)。 (3)不能返回動態(tài)地被分派了的數(shù)組或外部的數(shù)組的所占的字節(jié)數(shù)。 因為該變量里面的內(nèi)容是某一塊內(nèi)存的首地址,不是連續(xù)的,故只能返回指針?biāo)嫉淖止?jié)數(shù)。 (4)有的小伙伴說可以使用“sizeof(函數(shù)名)”,在這里更正一下,由代碼可知,這么做是錯誤的。
The sizeof operator shall not be applied to an expression that has function type or an incomplete type, to the parenthesized name of such a type, or to an expression that designates a bit-field member.
翻譯:sizeof不能用于函數(shù)類型和不完整的類型、這些類型帶括號的或者成員也不行。
二、strlen ()
size_t strlen(const char * _Str); 該函數(shù)實際完成的功能是從代表該字符串的第一個地址開始遍歷,直到遇到結(jié)束符’\0’。返回的長度大小不包括’\0’。 由上述例子中可以發(fā)現(xiàn),由于”p1”由字符串賦值(后面自帶“\0”),所以可以得到p1的字符串長度為5。而“p2”是由字符單個賦值,并且后面的“\0”不知道在什么地方,所以該字符串長度為錯誤值“16”。 運行時執(zhí)行。 頭文件:
#include <string.h>
三、延伸
數(shù)組名和指針不同,當(dāng)數(shù)組名作為函數(shù)形參時會退化為同類型的指針,這也是為什么傳遞數(shù)組名時會傳遞數(shù)組長度的原因。 單引號的表示一個字符,比如說字母a,在程序中以’a’表示。 雙引號圍起來的是一個字符串,后面有一個’\0’,這是例子中為什么“sizeof(p3)”比“strlen(p3)”大一的原因。 源碼工程。 http://download.csdn.net/download/itworld123/10164900
總結(jié)
以上是生活随笔 為你收集整理的sizeof和strlen()区别 的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔 推薦給好友。