首页 > 解决方案 > 为什么步骤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;
}

标签: c++pointerscastingdowncastupcasting

解决方案


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

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

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


推荐阅读