为什么步骤3中'*ptr'的值不等于3而是0?

问题描述

我发现steps:3中'*ptr'的值不等于3

#include <bits/stdc++.h>
using namespace std;
int main(int arg,char* args[])
{

    int* ptr;
    int x = 4;
    float y = 3.142;
    cout << y << "    " << &y << endl; //step:1
    ptr = &x;
    cout << ptr << "  " << *ptr << endl; //step:2
    ptr = (int*)(&y);
    cout << ptr << "  " << *ptr; //step:3 ->problem here
    return 0;
}

解决方法

ptr = (int*)(&y);
cout << ptr << "  " << *ptr; //step:3 ->problem here

第二行调用未定义的行为。 *ptr 取消引用 ptr 指向的内存,就像它指向 int 一样。由于它没有(它指向一个浮点数),这是未定义的行为。

从那时起,任何事情都可能发生。