c语言const变量改变,为什么我可以通过指针转换而不是C中的全局变量来更改本地const变量?...

我想通过使用指针来改变常量的值.

请考虑以下代码

int main()

{

const int const_val = 10;

int *ptr_to_const = &const_val;

printf("Value of constant is %d",const_val);

*ptr_to_const = 20;

printf("Value of constant is %d",const_val);

return 0;

}

正如预期的那样,常量的值被修改.

但是当我尝试使用全局常量的相同代码时,我遇到了运行时错误.Windows崩溃记者正在开放.在此语句"*ptr_to_const = 20;"中打印第一个printf语句后,可执行文件暂停

请考虑以下代码

const int const_val = 10;

int main()

{

int *ptr_to_const = &const_val;

printf("Value of constant is %d",const_val);

*ptr_to_const = 20;

printf("Value of constant is %d",const_val);

return 0;

}

该程序使用codeblocks IDE在mingw环境中编译.

谁能解释一下发生了什么?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值