使用指针更改const int的值 [英] Changing value of const int using using pointer

查看:126
本文介绍了使用指针更改const int的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用gcc编写了一个C程序,它给了我非常出乎意料的输出.代码是:

I wrote a C program in gcc and it's giving me very unexpected output. The code is :

#include<stdio.h>
int main(){
    const int x=10;
    int *p=&x;
    *p=11;
    printf("%d\n",*p);
    printf("%d",x);

    printf("\n%u\n",p);
    printf("%u", &x);
    }

这里的输出是:

11

10

37814068

37814068

为什么p和& x给出相同的地址(37814068)但值不同(5,10)?

Why do p and &x give the same address(37814068) but different values(5,10)??

推荐答案

修改const变量(直接或通过指针)将导致未定义的行为.在另一台计算机上可能无法获得相同的结果.

Modifying a const variable (directly or through a pointer) invokes undefined behavior. You may not get the same result in another machine.

这篇关于使用指针更改const int的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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