为什么要为未初始化的指针分配整数值 [英] Why can you assign an integer value to an uninitialized pointer

查看:119
本文介绍了为什么要为未初始化的指针分配整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行此操作时,它会完美打印出"2".

When I do this, it prints out "2" perfectly.

int main()
{
    int *p;
    int x = 2;

    *p = x;

    cout << *p;

}

但是当我第一次将* p初始化为null时,程序崩溃了.

But when I first initialized *p to be null, the program crashes.

int main()
{
    int *p=0;
    int x = 2;

    *p = x;

     cout << *p;

}

我想问一问,第一个程序什至首先成功运行了什么,为什么可以将值分配给未初始化的指针?

I want to ask what does the first program even successfully run in the first place, why can a value be assigned to an uninitialized pointer?

我的问题实际上与我过去获得的这个考试问题有关.您可以勾选多个答案,看来(b)& (c)两者都是正确的.但是现在我知道(c)是否起作用完全是由于运气.

My question is actually related to this past exam question that I got. You can tick more than one answer and it seems (b) & (c) both are correct. But now I know whether (c) works is purely due to luck.

推荐答案

第一个程序受到未定义行为的影响.看起来似乎可行,但不幸的是,看似理智的行为也是未定义的行为.

The first program is subject to undefined behavior. It seems like it works but, unfortunately, seemingly sane behavior is also undefined behavior.

如果取消引用未初始化的指针,就不要指望它始终能正常运行.

这篇关于为什么要为未初始化的指针分配整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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