C/C++語言中char*和char[]的區別

一般來說,很多人會覺得這兩個定義效果一樣,其實差別很大。
以下是個人的一些看法,有不正確的地方望指正。

char* s = “abcd”; 本質上是定義了一個char型指針,它存儲在字符常量區;

char s[] = “abcd”; 本質上是一個char型數組,存儲在棧空間裏,它實際上相當於
char s[] = {‘a’,‘b’,‘c’,‘d’,’\0’};

因此,這三者的sizeof(s):

char* s =  "abcd";// sizeof(s) = 8
char s[] = "abcd"; // sizeof(s) = 5
char s[] = {'a','b','c','d'};// sizeof(s) = 4

測試:

	char* ss = "this is char*";
	char ss1[] = "this is char[]";

	std::cout << "sizeof char*: " << sizeof(ss) << std::endl;
	std::cout << "sizeof char[]: " << sizeof(ss1) << std::endl;

結果:
在這裏插入圖片描述
說明:
對於char* ss = “this is char*”; ss表示地址,在64位系統中,地址有8個字節;
對於char ss1[] = “this is char[]”; ss1是數組首地址,sizeof(ss1)表示數組大小,
ss1末尾自動添加’\0’,因此是15個字節。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章