我已經很久沒有使用 c 了,所以也許我忘記了一些非常簡單的技巧。這是代碼,我嘗試列印 *p 的內容,但沒有列印出來。
#include <iostream>
using namespace std;
int main() {
char hello[] = "hello";
char *p = hello;
while (*p) {
*p = 1; // increase the character by one
p = 1; // move to the next spot
}
cout << "content of hello is: " << hello << endl;
cout << "content of hello is: " << *p << endl;
return 0;
}
uj5u.com熱心網友回復:
好訊息是我在寫這個問題時自己想通了。原因很簡單:p是char的指標型別,而p在while回圈中被改變了。所以這將列印出我:
cout << "content of hello is: " << *(p - 5) << endl;
只需在此處記下即可。
uj5u.com熱心網友回復:
您在此處處理的 C 字串以空字符 ( '\0') 終止。這就是為什么回圈 while*p是真的有效的原因。當p指向空終止符時,取消參考它會給我們0,這是錯誤的。
您的回圈遞增p,直到它指向空終止符。這意味著在回圈結束時,它必須指向'\0'哪個算作空 C 字串。然后,您的程式會列印該空字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/420552.html
標籤:
