-5
我有麻煩,在理解這個方案,請幫助:請解釋這個C++程序是如何工作的?
#include <iostream>
using namespace std;
int main(){
const char* s = 5+"hellow world";
cout<<s;
return 0;
}
我有麻煩,在理解這個方案,請幫助:請解釋這個C++程序是如何工作的?
#include <iostream>
using namespace std;
int main(){
const char* s = 5+"hellow world";
cout<<s;
return 0;
}
在代碼中的第三行,一個匿名的字符數組由編譯器創建。當您將5
添加到c字符串時,它會執行指針運算並將指針5
向前移動到字符串。因此,它會跳過c字符串中的5
字符,並僅將該數組中的其他字符存入s
。
歡迎來到stackoverflow.com。請花些時間閱讀[幫助頁面](http://stackoverflow.com/help),尤其是名爲[「我可以問些什麼話題?」]的章節(http://stackoverflow.com/help/)討論話題)和[「我應該避免問什麼類型的問題?」](http://stackoverflow.com/help/dont-ask)。請參閱[tour](http://stackoverflow.com/tour)並閱讀[如何提出良好問題](http://stackoverflow.com/help/how-to-ask)。最後,請學習如何創建[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 – Weaboo
'5+「hellow world」;'是指針算術。 ''hellow world''是一個字符串文字,'const char *',所以它和'const char * temp =「hellow world」;''相同,後面是'5 + temp;', &temp [5];' – user4581301
如果'foo'是一個指針(這裏就是這種情況),那麼'foo + 5'與'5 + foo'相同,並且與'foo [5]'相同與'5 [foo]'相同。 –