将指针分配给未初始化的变量会改变它的值吗? [英] Assigning pointer to uninitialized variable changes it value?

查看:49
本文介绍了将指针分配给未初始化的变量会改变它的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 VisualStudio2010 中使用 c++

I'm playing with c++ in VisualStudio2010

请解释 IT 发生的原因:

Please explain why IT happens:

int a, b;
int *p, *q;
cout << a << " " << b;

打印出0 0".嗯,这是可以理解的,未初始化的整数应该是 0;但是

prints out "0 0". Well it's understandable, uninitialized integer should be 0; but

int a, b;
int *p, *q;
p = &a;
cout << a << " " << b;

输出为1792816880 0"

output is "1792816880 0"

因此,如果我将指针分配给未初始化的变量,它会更改默认值.为什么?

So if I assign pointer to uninitialized variable it change value from default. Why?

编辑澄清:问题不是关于未初始化变量的值

Edit clarification: the question was not about value of uninitialized variable

int a; int *p;
cout << a; // would be 0, because it's loacal variable
p = &a;
cout << a; //not 0;

获取a的指针如何改变它的值?当我们初始化变量时,我们分配空间,一些位,它们可以是任何东西,但是p = &a"真的改变了这个空间中的位吗?

How getting pointer of a could change it value? when we init variable, we allocate space, some bits, they could be anything, but "p = &a" does it actually change bits in this space?

推荐答案

可以理解,未初始化的整数应该是 0

Well it's understandable, uninitialized integer should be 0

没有

不能保证,这取决于存储类,如果你的 int 是局部变量,它有一个自动存储,它不必是 0.

There is no guarantee of that, it depends on the storage class, If your int is local variable it has a auto storage and it need not be 0.

访问未定义的变量会导致未定义行为,而您的代码导致未定义行为.一旦出现未定义行为,所有赌注都将结束,行为无法解释.

Accessing Unitialized variables causes Undefined Behavior and Your code is causing an Undefined Behavior. Once there is an Undefined Behavior all bets are off and the behavior cannot be explained.

关于未定义行为,

C++ 标准第 1.3.24 节规定:

允许的未定义行为范围从完全忽略情况并产生不可预测的结果,在翻译或程序执行期间以环境特征的文件化方式行为(有或没有发布诊断消息),到终止翻译或执行(随着诊断消息的发布).

Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).


鉴于上述这是未定义的行为,并且不应编写任何依赖于此类行为的代码,事实上 One 甚至不应该考虑编写此类代码.我觉得它无关紧要&深入研究所有这些编译器的实现以寻求解释为什么它会以这种方式工作是徒劳的.


Given the above that this is Undefined Behavior and One should not write any code which relies on such behaviors, infact One should not even think of writing such code. I find it irrelevant & unproductive to dig in to the implementations of all those compilers to seek an explanation of why it works this way.

如果有人觉得这个回复很顽固,你可以随意投反对票.如果downvote数量超过upvotes,我会知道答案不受欢迎,我会删除它.

If someone finds this reply hardheaded, You are free to downvote. If the downvote count exceeds the upvotes, I would know the answer is unwelcome and I will delete it.

这篇关于将指针分配给未初始化的变量会改变它的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆