C++ 为什么第一个值是2814,而不是在我删除一段代码之后?

C++ 为什么第一个值是2814,而不是在我删除一段代码之后?,c++,visual-studio,visual-studio-2015,C++,Visual Studio,Visual Studio 2015,所以我有一个变量值4,我把它赋值为14,但它说它的值实际上是2814。。。 但是每当我删除一段代码时(我用注释标记它) “从这里开始”和“在这里结束”),一切又恢复正常。我想知道,是什么原因造成的&为什么会这样——当然,我是如何修复的 Here's the function: void incByOne(int &ref) { ++ref; } 代码如下: // *starts here* int *ptr = new int; // dynamically allocate

所以我有一个变量值4,我把它赋值为14,但它说它的值实际上是2814。。。 但是每当我删除一段代码时(我用注释标记它) “从这里开始”和“在这里结束”),一切又恢复正常。我想知道,是什么原因造成的&为什么会这样——当然,我是如何修复的

Here's the function:
void incByOne(int &ref) {
    ++ref;
}
代码如下:

// *starts here*
int *ptr = new int; // dynamically allocate an integer
*ptr = 28; // put a value in that memory location

if (!ptr) {
    std::cout << "Could not allocate memory.";
    exit(1);
}

std::cout << *ptr;
delete ptr;
// *ends here*

ptr = 0;

int value4 = 14;
int &ref = value4;
ref = value4;
std::cout << value4 << std::endl;
ref = 99;
std::cout << value4 << std::endl;
incByOne(value4);
std::cout << value4 << std::endl;
//*从这里开始*
int*ptr=new int;//动态分配一个整数
*ptr=28;//在该内存位置中输入一个值
如果(!ptr){

std::cout您可以从该行获得
28

std::cout << *ptr;

由于在输出
28
的行之后没有打印空格或换行符,因此您将得到
2814
作为输出。

当您打印值
ptr
时,它将打印
28
,但您不会在第一次打印
value4
之前插入换行符

这意味着您正在打印

2814
28
-值
*ptr

14
-值
值4


打印后插入一个
std::endl
,std::cout请用一个或注释之间的代码打印值28..使用
new int
似乎很愚蠢,为什么??@πάταῥεῖ 这不是没有定义的,他只是错过了一次机会newline@cocarin刚刚发现了这一点,从我的评论中删除了UB部分。VTC现在就知道了。
2814