‘\0’分析和char*認識

來源:互聯網
上載者:User

\0是C++中字串的結尾標誌,儲存在字串的結尾。比如char cha[5]表示可以放5個字元的數組,由於c/c++中規定字串的結尾標誌為'\0',它雖然不計入串長,但要佔記憶體空間,而一個漢字一般用兩個位元組表示,且c/c++中如一個數組cha[5],有5個變數,分別是
cha[0] , cha[1] , cha[2] , cha[3] , cha[4] , 所以cha[5]可以放5個字母或者放2個漢字(1個漢字佔2個位元組,1個字母佔一個位元組),cha[5]佔5個位元組記憶體空間。字串結尾要加上結尾標誌,則cha[5]實際佔6個位元組記憶體空間。


char* p="asdfasdfasdf";
char* p1=p+1;
char* p2=p1+1;
cout<<p<<endl;         //asdfasdfasdf
cout<<p1<<endl;      //sdfasdfasdf 
cout<<p2<<endl;     // dfasdfasdf 

char test[5];
test[0]='a';
test[1]='a';
test[2]='a';
test[3]='a';
test[4]='a';
cout<<test<<endl;    //aaaaa和一堆亂碼
return 0;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.