Search

10/21/2006

Re: [問題] C/C++中char*與char[]的差異

Re: [問題] C/C++中char*與char[]的差異

其實只要 C code 裡面出現 "string" 這種 literal constant string,
那 's' 't' 'r' 'i' 'n' 'g' '\0' 這個 sequence 必會出現在 constant pool 中,
而當你寫 char str[] = "string"; 且 str 非 global variable 時,
compiler 並不會直接產生一群分別填入這些字元到 stack 上的 code,
而是產生 load 之類的指令將這些值從 constant pool 搬至 stack。

Re: [問題] C/C++中char*與char[]的差異

"xxxxxx" 都是放在 constant pool 中,
而且通常 compiler 會將 constant pool 設為 read only。

char *ptr = "xxxxxx"; 是讓 ptr 指向 constant pool 裡第一個 'x' 的位置。
char str[] = "xxxxxx"; 是在 stack 中開 7 個 bytes 的空間,
並將 'x' 'x' 'x' 'x' 'x' 'x' '\0' 七個字元從 constant pool 中複製過來。

沒有留言: