首页 > 解决方案 > 初始化指针但未获得相同的零值

问题描述

我的问题是由于在两个单独的编译器中编译下面的代码而产生的。我在 Eclipse Helios 和 Online GDB Compiler 中输入了以下代码行,得到了不同的结果:

    int* ptr1 = new int;  
    int* ptr2 = new int(20);  

    cout << "Value of ptr1 = " << *ptr1 << "\n"; 
    cout << "Value of ptr2 = " << *ptr2 << "\n"; 

    delete ptr1; // Destroying ptr1 
    delete ptr2; // Detroying ptr2

对于在线 GDB,结果是:

Value of ptr1 = 0
Value of ptr2 = 20

但是,Eclipse Helios的结果是:

Value of ptr1 = 225472
Value of ptr2 = 20

它只是告诉我ptr1现在在其中包含一些垃圾值而不是零吗?

标签: c++pointersinitializationdelete-operator

解决方案


它只是告诉我 ptr1 现在在其中包含一些垃圾值而不是零吗?

是的,该值不保证为零。对于默认初始化

(强调我的)

否则,什么也不做:具有自动存储持续时间的对象(及其子对象)被初始化为不确定值

因此,两个编译器的观察结果都是合理的。


推荐阅读