1

私のコード:

#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 つですか?

4

5 に答える 5

2

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.

于 2013-05-06T01:33:45.833 に答える
0
于 2013-05-06T01:33:32.033 に答える
0

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

于 2013-05-06T01:34:50.150 に答える