C語言-字元數組和字串

來源:互聯網
上載者:User

標籤:cti   gfs   pos   printf   ber   ret   需要   沒有   rap   

1:概念

用來存放字元的數組成為字元數組。

例如:

char a[10]={‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘,‘j‘,‘g‘,‘f‘,‘k‘};//

【注意】在C語言中沒有字串,所以用字元數組來存放字串。

例如:

char a[30]={"shisihuansheng.blog"};

char a[30]="shisihuansheng.blog";//這個寫法更為簡潔,方便,開發時候經常使用。

a[0]=s;a[1]=h 依次類推。

在C語言中,字串總是以‘\0‘作為串的結束符。上面的兩個字串,編譯器已經在末尾自動添加了‘\0‘

puts 和 printf 在輸出字串時會逐個掃描字元,直到遇見 ‘\0‘ 才結束輸出。請看下面的例子:

純文字複製
  1. #include <stdio.h>
  2. int main(){
  3. int i;
  4. char str1[30] = "http://c.biancheng.net";
  5. char str2[] = "C Language";
  6. char str3[30] = "You are a good\0 boy!";
  7. printf("str1: %s\n", str1);
  8. printf("str2: %s\n", str2);
  9. printf("str3: %s\n", str3);
  10. return 0;
  11. }

運行結果:
str1: http://c.biancheng.net
str2: C Language
str3: You are a good

str1 和 str2 很好理解,編譯器會在字串最後自動添加 ‘\0‘,並且數組足夠大,所以會輸出整個字串。對於 str3,由於字串中間存在 ‘\0‘,printf() 掃描到這裡就認為字串結束了,所以不會輸出後面的內容。

需要注意的是,用字串給字元數組賦值時由於要添加結束符 ‘\0‘,數組的長度要比字串的長度(字串長度不包括 ‘\0‘)大1。例如:

char str[] = "C program";

該數組在記憶體中的實際存放情況為:

字串長度為 9,數組長度為 10。

 

C語言-字元數組和字串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.