簡體   English   中英

有人可以向我解釋為什么這段代碼沒有 output 任何東西

[英]Can someone explain to me why this code doesn't output anything

我已經為這里出了什么問題而崩潰了。 在 output 中,我幾乎什么也沒得到。 很奇怪,通過正常的cout沒有什么是 output 。

請幫幫我。 謝謝你。

int main() {
    int x = 111111;
    array<int, 10> numbers;
    numbers.fill(8);
    const auto numbers_copy = numbers;
    int y = 222222;
    
    for (int* i = &y; i <= &x; i++) {
        cout << *i << ' ';
    }
    cout << endl;
}

這個循環:

for (int* i = &y; i <= &x; i++) {

具有未定義的行為 (UB)

比較指向不相關對象的指針有未指定的結果。 在這種情況下, i指向 2 個不同的int對象, xy ,因此第一次比較可能為真也可能不為真,因為無法保證堆棧上的 2 個對象將一個接一個地連續放置在 memory 中,或者以任何特定順序。

這同樣適用於循環的第二次迭代。 在第二次迭代中,當您第二次執行i++時,這是未定義的行為,因為當i指向int時您不能遞增那么多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM