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#">
- #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';
- }
#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';}