C中常量指针的困惑

标签 c pointers constants

对于 const int *ptr
你不能改变ptr指向的值

int main()
{
    const int *p;
    int a=5;
    p=&a;   
    printf("%d",++(*p));
}

上面的程序抛出错误。这很公平。

但是为什么下面的代码不会抛出错误。

int main()
{
    const int const *p;
    int a=5;
    p=&a;
    a=100;  // changing the content pointed by the constant pointer

    printf("%d",(*p));
}

我正在更改 const 指针指向的值。即我正在更改 var a 的值 5 到 100?

最佳答案

语句 a = 100;意味着您正在使用变量 a 将值更改为 100,该变量不是常量。因此您将能够更改 a 的值。

但是如果您尝试运行以下代码:

int main()
{
        const int const *p;
        int a=5;
        p=&a;
        *p=100;
//      a=100;
        printf("(*p)=%d",(*p));
        return 0;
}

这会给您带来错误,因为您要更改值的指针指向只读位置。因为您已将指针位置的值声明为常量。

这里 a 和 p 是两个不同的变量,它们有自己的属性。

关于C中常量指针的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20580070/

相关文章:

c - 隐式指针到 Const-T 转换

创建不使用本地循环接口(interface)的 UDP 客户端?

c - 在 C 中多次正确返回一个字符串

c - 使用 Xinerama 的多个显示器可能的分辨率

python - Python 中的 C 风格指针,这是正确的吗?

c++ - Caesar Cipher C++(使用字符指针和移位作为参数)

c++ - 变量卡在 If 中

c - 是否可以在不使用数组的情况下读取文本文件? C

c - 使用 toupper 将字符数组传递给函数

c++ - 我们需要 std::as_const() 做什么?