字串表示形式—字元數組和字元指標的區別

來源:互聯網
上載者:User

Char *p1 = “A String.” 和 char p2[] = “another String.” 寫法的不同

p1指向的這個字串是個常量, 不可改變。 程式在編譯期間就為"A String."這個字串分配了固定的空間, 它被儲存在全域靜態區中. 編譯器只是把指標p1的指向的地址賦為“A String.”的首地址,並沒有為指標p1指向的地址分配可供操作的記憶體(除非使用malloc),如果試圖改變p1指向的字串,則會出錯(試圖改變不可寫記憶體內容的錯誤)。

而p2是個變數, 其內容可以被更新和改變, p2可以理解為一個不可改變其指向位置的指標, 即char * const p2, 它所佔用的記憶體在程式運行時被自動分配和釋放, 而p1佔用的記憶體要等到整個程式結束時才被釋放. 編譯器為數組b分配了可供操作的儲存空間.

C代碼 {
dp.sh.Toolbar.CopyToClipboard(this);return false;
}" href="http://www.javaeye.com/topic/446704#">
  1. #include <stdio.h>   
  2.   
  3. void main()    
  4. {   
  5.     void copy_string(char *si, char *di);   
  6.     char *ss,*dd;   
  7.     char from[] = "I am a student.";   
  8.     char to[]   = "You are a teacher.";   
  9.   
  10.     ss = "I am a student.";   
  11.     dd = "You are a teacher.";   
  12.        
  13.     printf("a:%s/nb:%s/n",ss,dd);   
  14.     copy_string(ss,to); //這樣寫沒有問題   
  15.     //copy_string(ss,dd); //有問題   
  16.     //copy_string(from,to);//沒問題   
  17.     printf("/n");   
  18.     printf("a:%s/nb:%s/n",ss,to);   
  19. }   
  20.   
  21. void copy_string(char *si, char *di)   
  22. {   
  23.     for(; *si != '/0'; si++,di++)   
  24.         *di = *si;   
  25.     *di = '/0';   
  26. }  
#include <stdio.h>void main() {void copy_string(char *si, char *di);char *ss,*dd;char from[] = "I am a student.";char to[]   = "You are a teacher.";ss = "I am a student.";dd = "You are a teacher.";printf("a:%s/nb:%s/n",ss,dd);copy_string(ss,to); //這樣寫沒有問題//copy_string(ss,dd); //有問題//copy_string(from,to);//沒問題printf("/n");printf("a:%s/nb:%s/n",ss,to);}void copy_string(char *si, char *di){for(; *si != '/0'; si++,di++)*di = *si;*di = '/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.