我们可以改变通过指针常量的值? [英] Can we change the value of a constant through pointers?

查看:108
本文介绍了我们可以改变通过指针常量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  常量和指针用C


 的#include<&stdio.h中GT;
诠释的main()
{
    const int的一个= 12;
    INT * P;
    P =&放大器;一个;
    * p = 70;
}

将它的工作?


解决方案

这是未定义的行为,这意味着基于您不能当您尝试这个predict会发生什么标准。根据特定的计算机,编译器和程序状态的不同,可能做不同的事情。

在这种情况下,你会经常发生的是,答案是是。一个变量,常量与否,是在内存中只是一个位置,你可以打破常量性的规则和简单地覆盖它。 (当然,这会如果程序的其它部分取决于其常数数据是恒定引起严重的错误!)

然而,在某些情况下 - 最典型的为常量静态数据 - 编译器可以把这些变量在内存的只读区域。 MSVC,例如,通常所说的静态常量在整数可执行文件,这意味着操作系统将抛出一个保护错误,如果你试图写它,程序会崩溃的文本段。

在编译器和机器,完全不同的事情可能发生的其他一些组合。有一件事你的可以的predict可以肯定的是,这种模式会惹恼谁就拥有读你的code。

Possible Duplicate:
constants and pointers in C

#include <stdio.h>
int main()
{
    const int a = 12;
    int *p;
    p = &a;
    *p = 70;
}

Will it work?

解决方案

It's "undefined behavior," meaning that based on the standard you can't predict what will happen when you try this. It may do different things depending on the particular machine, compiler, and state of the program.

In this case, what will most often happen is that the answer will be "yes." A variable, const or not, is just a location in memory, and you can break the rules of constness and simply overwrite it. (Of course this will cause a severe bug if some other part of the program is depending on its const data being constant!)

However in some cases -- most typically for const static data -- the compiler may put such variables in a read-only region of memory. MSVC, for example, usually puts const static ints in .text segment of the executable, which means that the operating system will throw a protection fault if you try to write to it, and the program will crash.

In some other combination of compiler and machine, something entirely different may happen. The one thing you can predict for sure is that this pattern will annoy whoever has to read your code.

这篇关于我们可以改变通过指针常量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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