如何解决为什么步骤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
一样。由于它没有(它指向一个浮点数),这是未定义的行为。
从那时起,任何事情都可能发生。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。