2017-06-01 106 views
0

你能幫我解釋下面的代碼的結果嗎?結果cout <<「Hello」+ 1 << endl; (C++)

cout<< "Hello" + 1<< endl; 

爲什麼結果出來爲 「ELLO」,我知道打印出Hello1那麼我應該使用: COUT < < 「你好」 < < ENDL; 但誰能幫我解釋一下上面代碼的順序: 非常感謝。

+5

'「你好」'是指向的6'char's陣列(未相當,但足夠接近)。給這個指針加'1'會產生一個指向下一個'char'的指針,即'e'。那個指針然後被解釋爲指向一個NUL終止的字符串'「ello」' –

回答

4

你的例子是大致相當於此:

// `p` points to the first character 'H' in an array of 6 characters 
// {'H', 'e', 'l', 'l', 'o', '\0'} forming the string literal. 
const char* p = "Hello"; 
// `q` holds the result of advancing `p` by one element. 
// That is, it points to character 'e' in the same array. 
const char* q = p + 1; 
// The sequence of characters, starting with that pointed by `q` 
// and ending with NUL character, is sent to the standard output. 
// That would be "ello" 
std::cout << q << std::endl; 
+0

非常感謝Igor的解釋,我怎樣才能接受答案?我在這裏看不到Accept按鈕。 –

相關問題