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

/ 1,307评论 / 8274阅读 / 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. Nutrim说道:

    Appreciated this entry. It’s extremely well-researched and filled with useful information. Thank you for sharing such helpful information.

  2. porn说道:

    I was pretty pleased to uncover this site. I wanted to thank you for your time due to this wonderful read!! I definitely appreciated every bit of it and i also have you book-marked to check out new information in your website.

  3. Home Title Lock说道:

    This is great. I learned a lot from perusing it. The content is very informative and well-organized.

  4. Really liked perusing this post. It’s extremely articulate and filled with valuable insight. Many thanks for sharing this.

  5. Excellent entry. It’s very articulate and packed with beneficial information. Thanks for offering this information.

  6. Тут можно преобрести сейф оружейный купить оружейный ящик купить

发表回复

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