c++ - 为什么步骤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
. 因为它没有(它指向一个浮点数),所以这是未定义的行为。
从那时起,任何事情都可能发生。
推荐阅读
- mysql - SQL 客户订单
- c# - 在 linq 中使用条件过滤实体框架核心
- c - 如何循环文件流
- swift - 使用 FirebaseFirestoreSwift 从地图字段 ind Cloud Firestore 加载数据
- java - 如何将父实例引用传递给 ui.xml 中的子元素?
- javascript - 8.12.5:共同朋友代码HS
- dolphindb - 如何根据另一个表上的信息更新列(DolphinDB)
- django - 如何从另一个不同的 ModelForm 获取数据
- node.js - Socket.io 调用顺序不清楚
- aws-lambda - 对 AWS Lambda 进行无服务器部署的 IAM 用户需要哪些策略?