指向c ++中const int的指针

问题描述 投票:0回答:2

在C ++中,我有下一个代码

int main() {
    int i = 1;
    cout<<"i = "<<i<<endl; //prints "i = 1"

    int *iPtr = &i;
    cout<<"*iPtr = "<<*iPtr<<endl; //prints "*iPtr = 1"

    (*iPtr) = 12; //changing value through pointer

    cout<<"i = "<<i<<endl; //prints "i = 12"
    cout<<"*iPtr = "<<*iPtr<<endl; //prints "*iPtr = 12"

    system("pause");
    return 0;
}

现在与常数整数 i]相同的代码

int main() {
    const int i = 1;
    cout<<"i = "<<i<<endl; //prints "i = 1"

    int *iPtr = (int*)&i; //here I am usint a type conversion
    cout<<"*iPtr = "<<*iPtr<<endl; //prints "*iPtr = 1"

    (*iPtr) = 12; //changing value through pointer

    cout<<"i = "<<i<<endl; //prints "i = 1"
    cout<<"*iPtr = "<<*iPtr<<endl; //prints "*iPtr = 12"

    system("pause");
    return 0;
}

如您所见,在第二种情况下使用常量整数,* iPtr和const i有两个不同的值,但是指针* iPtr显示为常量i。请告诉我第二种情况会发生什么,为什么?

在c ++中,我有下一个代码int main(){int i = 1; cout <

c++ pointers const
2个回答
4
投票

您的第二个代码具有未定义的行为


1
投票

您正在尝试删除变量的const限定词。在C ++中,您应该使用const_cast来做到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.