修改在C常数 [英] Modified a constant in c

查看:134
本文介绍了修改在C常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const int z = 420;

printf("\n%d | %d",z ,*(&(*(&z+1))-1) );
// O/P:420 | 420

printf("\n%u | %u",&z,(&(*(&z+1))-1) );             //address
// O/P:1310548  | 1310548

*((char *)&z+1) = 21;       //I change value for the 1st-Bit
                                    //corrupting constant

 printf("\n%d | %d",z ,*(&(*(&z+1))-1) );
//the complex(not really) expression evaluates to z
// O/P:420| 5540

printf("\n%u | %u",&z ,(&(*(&z+1))-1) );                
//the complex(not really) expression evaluates to &z
// O/P:1310548 | 1310548

为什么会出现这种情况?

似乎我已经成功地使用C不断修改

it seems that I have successfully modified constant in C

通过修改我的意思是我在常量改位地址范围

by modify I mean I have changed the bits in the constants address range

为复杂的(不是真的)统一/身份前pression
损坏后的变化值。

as the "complex(not really) unity/identity expression" changes value after corruption.

但在Z保持不变。为什么呢?

but the z remains same. Why?

怎么来的同一个地址有不同的价值观去引用时。 ?

how come same address have different values when de-referenced. ?

PS:U可以使用任何身份前pression

PS: u can use any identity expression

eg.printf("%d",*(int*)((char*)&(*((char*)&z+1))-1));

OK让我重新句话吧:

ok let me re-phrase it:

z = 420

&z = 1310548

*(&(*(&z+1))-1) = 420

(&(*(&z+1))-1)  = 1310548

现在我做的腐败恒

*((char *)&z+1) = 21;

现在经过腐蚀:

z = 420     // NO CHANGE EVEN THOUGH I have corrupted

&z = 1310548

*(&(*(&z+1))-1) = z = 5540    // THE CHANGE

(&(*(&z+1))-1)  = &z = 1310548

为什么?

推荐答案

有不在这儿一会儿不少神秘色彩。通过使用强制转换来告诉编译器什么你改变不是常量合格的,你造成未定义行为:

There's not a while lot of mystery here. By using casts to tell the compiler that what you're changing isn't const qualified, you're causing undefined behavior:

6.7.3 / 5类型的限定(C99):

6.7.3/5 "Type qualifiers" (C99):

如果试图修改与通过使用一个const-合格音响编类型定义的对象
  与非const限定类型的左值的,行为是不确定的。

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.

有些实现可能已经放在变量以Z 在只读存储器和你要么得到无明显变化或某种访问冲突。

Some implementations might have placed the variable z in read only memory and you'd either get no apparent change or some sort of access violation.

在任何情况下,不确定的行为意味着全盘皆输 - 你的情况,你能看到一个常量的外观修改

In any case, undefined behavior means all bets are off - in your case you're able to see the apparent modification of a const value.

这篇关于修改在C常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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