私のコード:
#include <stdio.h>
main()
{
const int x = 10;
int *p;
p=&x;
*p=20;
printf("Value at p: %d \n",*p);
printf("Value at x: %d", x);
}
私が得る出力は次のとおりです。
p の値: 20
x の値: 20
したがって、定数変数の値が変更されます。これはポインターを使用することの欠点の 1 つですか?
You used a int* to point to a const int. you should get:
error: invalid conversion from ‘const int*’ to ‘int*’
when you do:
p = &x;
You probably needs to update your compiler, a decent compiler should have told you this error or at least gave you warning about this.
That's because you are using the C language in the wrong way and the compiler let you compile this code while giving only a warning
warning: assignment discards ‘const’ qualifier from pointer target type [enabled by default]
And there are answers for that on SO, such as warning: assignment discards qualifiers from pointer target type