2014-03-19 55 views
0

我一直在學習C++一段時間,並且當談到指針時,我遇到了一個「障礙」。我使用這個作爲我的http://www.cplusplus.com/doc/tutorial/pointers/學習資料,但我仍然有問題。所以測試一下我想將一個數組的內容複製到另一個數組中。我寫了以下內容。使用指針將一個數組的內容複製到另一個

char arrayA[15] = "abcdef"; 
char arrayB[15]; 

char *a = arrayA; 
char *b = arrayB; 

cout << "before loop:" << endl; 
cout << a << endl; 
cout << b << endl; 

while (*a != '\0') { 
    // Copy the contents of a into b 
    *b = *a; 

    // Step 
    a++; 
    b++; 
} 

// Assign null to the end of arrayB 
*b = '\0'; 

cout << "after loop:" << endl; 
cout << a << endl; 
cout << b << endl; 

我收到以下結果。

before loop: 
abcdef 

after loop: 

當我cout循環前的內容我得到了預期的結果。 a包含「abcdef」和b就是沒有,因爲沒有價值。現在在循環之後,ab都沒有顯示任何結果。這是我迷失的地方。我使用*來解引用ab,並將值a分配到b。我哪裏做錯了?我需要使用&嗎?

解決方案:在循環完成

後,指針*a指向arrayA的端部和指針*b指向arrayB的末尾。所以要獲得arrayB的完整結果只需cout << arrayB。或者創建一個永不改變的指針,並且在循環結束時始終指向arrayB char *c = arrayBcout << c

+0

注意,NULL不是空字符,它是寫爲 '\ 0'。 NULL是一個表示空指針的C宏,不應該在C++中使用(對於指針,使用新的文字nullptr,或者簡單地使用0)。 –

+0

@Peter Schneider謝謝。做了必要的更改。 – MrPilot

+0

哦,並且不要使用未初始化的數組,例如用於輸出(比如「beforeLoop」之後的arrayB)。在第一個字符中寫入'\ 0',以便它變成空字符串。你的程序只能巧合使用(除非數組是全局的,在這種情況下它們被置零)。 –

回答

3

循環ab發生變化後,它們將指向字符串的末尾。您需要製作指針的副本以逐步執行,以便在迭代時不會更改ab的位置。

3

問題是你正在輸出用於遍歷數組的臨時變量。它們現在處於複製數據的末尾。您應該輸出值arrayAarrayB

+0

感謝您的輸入。我很感激。 – MrPilot

0

記住數組的開始。在這一刻,你正在增加指針並在循環結束後打印數組末尾指向的內容。

char arrayA[15] = "abcdef"; 
char arrayB[15]; 

char *a_beg = arrayA; 
char *b_beg = arrayB; 
char *a; 
char *b; 

cout << "before loop:" << endl; 
cout << a_beg << endl; 
cout << b_beg << endl; 

a = a_beg; 
b = b_beg; 
while (*a != '\0') { 
    // copy contents of a into b and increment 
    *b++ = *a++; 
} 
// assign null to the end of arrayB 
*b = '\0'; 

cout << "after loop:" << endl; 
cout << a_beg << endl; 
cout << b_beg << endl; 
相關問題