gpt4 book ai didi

c++ - 为什么通过指针分配给常量没有效果?

转载 作者:行者123 更新时间:2023-11-30 03:29:16 27 4
gpt4 key购买 nike

<分区>

在下面的示例中,“ptr”指向常量变量“local”。为什么通过分配 '*ptr' 修改 'local' 不会更改 'local' 的值?

#include <stdio.h>
int main(void)
{
const int local = 10;
int *ptr = (int*) &local;

printf("address of local: %p \n", &local);
printf("value of ptr: %p \n", ptr);
printf("Initial value of local : %d \n", local);
printf("Initial value of *ptr : %d \n", *ptr);

*ptr = 100;
//*((int*)&local) = 1000;

printf("Modified value of local: %d \n", local);
printf("Modified value of *ptr: %d \n", *ptr);
printf("address of local: %p \n", &local);
printf("value of ptr: %p \n", &(*ptr));

return 0;
}

输出:

address of local: 0x7ffd946bd9c4
value of ptr: 0x7ffd946bd9c4
Initial value of local : 10
Initial value of *ptr : 10
Modified value of local: 10
Modified value of *ptr: 100
address of local: 0x7ffd946bd9c4
value of ptr: 0x7ffd946bd9c4

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com