我很難理解pointer2包含的內容。第二個printf列印llo World,但第三個列印Hey you guys!。如果strcpy復制y you guys!\n到llo World. 根據我對以下程式的理解,最后一個輸出應該是llo Worldy you guys!\n,不是嗎?
int main()
{
char str_a[20]; // a 20 element character array
char *pointer; // a pointer, meant for a character array
char *pointer2; // and yet another one
strcpy(str_a, "Hello World\n");
pointer = str_a; // set the first pointer to the start of the array
printf("%p\n", pointer);
pointer2 = pointer 2; // set the second one 2 bytes further in
printf("%s", pointer2); // print it
strcpy(pointer2, "y you guys!\n"); // copy into that spot
printf("%s", pointer); // print again
}
uj5u.com熱心網友回復:
指標pointer指向陣列的第一個字符str_a。
pointer = str_a;
該陣列包含字串"Hello World\n"。
指標pointer2指向字串的第三個元素
pointer2 = pointer 2;
那就是它指向"llo World\n"。
然后這個子字串被覆寫str_a[0]并保持不變str_a[1]。
strcpy(pointer2, "y you guys!\n");
所以陣列str_a包含字串"Hey you guys!\n"
其實上面的 strcpy 呼叫等價于
strcpy( &str_a[2], "y you guys!\n");
因為反過來這個宣告
pointer2 = pointer 2;
相當于
pointer2 = &str_a[2];
或者
pointer2 = &pointer[2];
而這個電話
printf("%s", pointer);
輸出字串。
即"He"(從 str_a[0] 開始)加上"y you guys!\n"(從 開始str_a[2])產生結果字串。
uj5u.com熱心網友回復:
char str_a[20]; // a 20 element character array
char *pointer; // a pointer, meant for a character array
char *pointer2; // and yet another one
第一行創建并分配記憶體給 20 個字符。另外兩個只創建指向空的指標。這些指標可用于指向記憶體區域,這意味著您可以在其中存盤地址(數字)。
strcpy(str_a, "Hello World\n");
此行將“Hello World\n”復制到str_a(分配的記憶體 - 確定)。
pointer = str_a; // set the first pointer to the start of the array
printf("%p\n", pointer);
現在,我們將str_a的地址復制到指標變數。這兩個變數可以以相同的方式使用。它們指向相同的記憶。列印指向的記憶體地址。
pointer2 = pointer 2; // set the second one 2 bytes further in
printf("%s", pointer2); // print it
在這里,我們也復制了一個地址(一個數字),就像之前所做的那樣,但是我們在地址上加了 2。所以,如果str_a和指標指向一個位置 X,那么現在,pointer2將指向 X 2(X 是一個數字,塊的記憶體地址)。我們知道這個塊 ( str_a ) 的內容是“Hello World\n”,然后,指標2 指向右邊 2 個字符的位置:“llo World\n”。這僅僅意味著pointer2存盤的地址號指向這個位置,但分配的塊還包含整個句子。
strcpy(pointer2, "y you guys!\n"); // copy into that spot
printf("%s", pointer); // print again
現在,我們可以看到指標2 指向的地址的字符副本。因此,前兩個字符在復制位置之外,“y 你們!\n”將被復制到 str_a 的位置 2 ,即pointer2的位置 0 。
結果:“He”(str_a的前兩個字符未觸及) “y 你們!\n”(復制到pointer2的字符)=“嘿你們!\n”
如果您列印pointer2,您將看到“你們!\n”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462812.html
