[c++]使用int()显式类型转换指针来修改const char的值

/ 2评论 / 426阅读 / 0点赞

摘要

记得之前看过一篇文章说所有的指针其实都可以视为一个int类型,这句话催生了我很多想法,这篇博文即为其一。

示例

#include<iostream>
using namespace std;

int main()
{
    const char str[] = "123456";
    cout << str << endl;
    char* p = (char*)(int(str));
    *p = 48;    //0的ASCII
    cout << str << endl;

    return 0;
}

不可修改的特例

#include<iostream>
using namespace std;

int main()
{
    const char* str = "123456";
    cout << str << endl;
    char* p = (char*)(int(str));
    *p = 48;    //0的ASCII
    cout << str << endl;

    return 0;
}

写在最后

* c++本身也提供了一些方法可以去掉str的const限制:比如const_cast<>,它的使用方法在百度上很多,如果需要请自行百度了解。

* 指针着实是相当有意思的东西。

  1. Clollag说道:

    cialis generic cost Molecular targeting of Akt by thymoquinone promotes G 1 arrest through translation inhibition of cyclin D1 and induces apoptosis in breast cancer cells

  2. Coikemn说道:

    A Expression of CDK2 and MAFG AS1 were positively correlated cialis online reviews

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注